Keep many values in one array, read any of them by its index counted from 0, and read the type of a list as string[]. Add items with push, see why const still lets a list grow, avoid reading one past the end, and make TaskKit keep the tasks it adds instead of only counting them.
TypeScript
Fundamentals
Arrays and the `T[]` type. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
At the end of the last module TaskKit could check what you typed
and say what went wrong. What it cannot do is remember. It reads
one task, prints it, and adds 1 to added. The task itself is
gone the moment it is printed: a number can say that one task was
added, never which one. Keeping five tasks would take five boxes,
task1 to task5, and a sixth task would mean editing the code.
Think of the lockers at a swimming pool. Nobody builds a separate
cupboard for every visitor. There is one cabinet with a row of
doors, each door has a number painted on it, and you open door 7
without searching the others. A program keeps a list the same way.
By the end of this lesson you can keep many values in one box,
read any of them by its number, say the box's type, and TaskKit
stores each task it adds instead of only counting it.
One box, many values
An array is a value that holds a list of other values, in
order. Each value in the list is an item; you will also see
the word element, which means the same. You write an array
with square brackets around the items and a comma between them.
This course also calls an array a list; both words mean the same
thing:
It prints 3, then buy milk. The picture of memory boxes from
Module 2 still works: tasks is one box with one label, and what is in it
is the whole list. The list just happens to have three things in
it, the way one cabinet has many doors.
You have used an array before without the name. In lesson 2.8,
process.argv (argv, short for argument vector, the list of
words typed) was the list Node fills from the command line, and
Node printed it in square brackets with a comma between the
items. process.argv[2] read one of its items, and
process.argv.length counted them. Everything you did with that
list works on any array.
Every item has an index
The number painted on each door is the item's index: its place in
the list, counted from 0, as in a string in lesson 2.4 and in
process.argv in lesson 2.8. The
first task is tasks[0], the second tasks[1], the third
tasks[2]. tasks.length counts the items, just as a string's
.length counted its characters, so a list of three has nothing
at index 3:
What is theretasks[0]
"buymilk"
The first one
tasks[1]
"callmom"
The second one
tasks[2]
"payrent"
The last one
tasks[3]
undefined
Nothing: the list ends at index 2
Three tasks sit at 0, 1 and 2; tasks[3] is past the end
Counting from 0 means the last item always sits one place before
the length: at tasks.length - 1. Written that way, the line
reads the last task however long the list grows. There is a
shorter way too. .at() from Module 3 also counts from the end
when you give it a negative number, so tasks.at(-1) is the last
item, tasks.at(-2) the one before it. Run them, with one more
line that reads past the end:
The first three lines print pay rent. The fourth asks for a door
the cabinet does not have, and prints undefined, with no error.
Square brackets never count from the end: tasks[-1] is
undefined too. Remember that quiet undefined: the common
mistake of this lesson comes from it.
The type of a list: string[]
Copy tasks.ts from the top of this lesson into VS Code (Visual
Studio Code, your editor) and hover over tasks. The
hover says const tasks: string[]. Read it as "an array of
strings": the type of every item, then a pair of empty square
brackets. A list of numbers is number[], a list of true and
false is boolean[]. The title of this lesson writes the
pattern as T[]: the T stands for whichever type the items
have. You will meet letters like T properly in Module 10; for
now, read T[] as "a list of T".
Compare it with what inference did in Module 2. There,
const version = "0.1" got the type "0.1", the value itself,
because a const box never changes. An array in a const box is
different: as you will see in a moment, items can be added to it.
So TypeScript gives the list the whole kind, string[], and every
string is welcome in it.
The type is a promise about every item, and TypeScript checks
every item against it, starting on the line that makes the list.
The first is refused before it runs, with Type 'number' is not assignable to type 'string'. under the 15. Without that check,
a later tasks[1].toUpperCase() would reach a number, which has
no such method.
Lesson 2.6 had a rule for when to write a type yourself:
when the first value is not the whole story. An empty list is the
clearest case there is. [] holds nothing that says what will go
in, so write it: const tasks: string[] = []; is an empty list
that will only ever take strings.
Adding and changing items
A list written into the code holds what you knew when you wrote
it. Tasks arrive while the program runs, so a list needs a way to
grow. push is that way: tasks.push("buy milk") adds an item
at the end of the list, and its length goes up by one. Press
Next step to watch an empty list fill up, or let it play:
CodeThe program, line by line. The marked line is the one the computer is running now; the lines above it have run.ts
MemoryThe boxes in memory, each with its name. A box appears when a line makes it; the one just filled or changed is orange.
tasks["buy milk", "call mom", "pay rent"][]
OutputEverything the program has printed so far.
Nothing printed yetNothing printed yet
Every step as text
Line 1.tasks = [].
A box labelled tasks is made, holding an empty list.
Line 2.tasks = ["buy milk"].
push puts "buy milk" at the end of the list. It is the only
item, so it sits at index 0.
Line 3.tasks = ["buy milk", "call mom"].
The next push adds "call mom" after it, at index 1. Still one
box.
Line 4.tasks = ["buy milk", "call mom", "pay rent"].
A third task, at index 2. The box holds three values now.
Line 5.tasks = ["buy milk", "call mom", "pay rent"].
.length counts the items in the list, and 3 is printed.
Prints 3
One box, and push adds each new task at the end
TypeScript checks every push against the type, too:
tasks.push(5) on this list is refused with Argument of type 'number' is not assignable to parameter of type 'string'. (a
parameter is the slot push takes its value in; Module 5 explains
it).
To change an item that is already there, write its index on the
left of =, the way you refill a let box. The new value takes
that place, and the length stays the same:
It prints 2, then call dad. Press Step to see line 4 put
the new value at index 1, where "call mom" was.
Look at the first line again: tasks was made with const, and
the lines after it changed the list three times. Module 2 said a
const box is locked, and it is. What const locks is the box:
it will hold this same list for as long as the program runs. The
list inside can still grow and change. Only a line that puts a
whole new list in the box is refused, with TS2588 (TS for
TypeScript, then the error's number):
Does: Adds an item to the list that is already in the box
Never: Never puts a different list in the box
const tasks = ["buy milk"];tasks = ["call mom"];
Put a new list in the box: =
Does: Tries to put a different list in the box
Never: Never allowed on a const box: TS2588
TypeScript: Cannot assign to 'tasks' because it is a constant.
A const box keeps its list; the list itself can still grow
So the rule from Module 2 does not change: start with const,
and switch to let only when a line puts a new value in the box
itself. Adding to a list is not such a line.
TaskKit keeps its tasks
Now TaskKit's step for this module begins. Instead of counting
tasks in added, TaskKit keeps them in a list, and the count
comes from the list. Open index.ts in ~/projects/taskkit and
replace the box added with an empty list of strings:
Then, under the switch, read the count from the list, and print
the list at the very end:
index.tsts
const added = tasks.length;const room = limit - added;console.log( `Tasks added: ${added} of ${limit}, room for ${room} more`);// Rounded: without it, a limit of 3 prints 66.66666666666666const percent = Math.round((added / limit) * 100);console.log(`List ${percent}% full`);console.log("Your list:", tasks);
added is a const now, made once from tasks.length, so no
line has to remember to add 1 to it any more. A counter kept by
hand can drift from the truth; a length read from the list cannot.
Check the file with tsc (the TypeScript compiler, started by
npx) and run it:
============================TaskKit 0.1Your tasks, in your terminal============================Added: Buy milkTasks added: 1 of 5, room for 4 moreList 20% fullYour list: [ 'Buy milk' ]
The last line is Node printing an array, the way it printed
process.argv. Run node index.ts help and it ends with
Your list: [], an empty list.
Every run starts with that empty list again. When a program ends,
its boxes are emptied, as lesson 1.1 said, and the list
is in one of them. Keeping the tasks between runs needs a file,
which Module 12 adds. Within one run, though, TaskKit now holds
real tasks rather than a number, and the next lessons of this
module work with them: going through the list, finding a task,
and sorting them.
Predict before you run
The list below is changed twice before anything is printed.
Follow it line by line and decide what the last line shows.
The length of a list is the count of its items, and it is very
tempting to use it as the index of the last one. A list of three
has a length of 3, but its items sit at 0, 1 and 2.
Common mistake
Reading the last task at tasks.length
You want the newest task, in capitals, so you read the item at the
list's length:
Why did tsc stay quiet? Hover over last: it says string. As
Module 3 showed with process.argv[3], square brackets assume the
item is there. tasks.at(-1) admits that it may not be: its type
is string | undefined, so tsc refuses .toUpperCase() on it
until you check it, the way the last lesson checked typedTask.
When a list prints undefined where you expected an item, look at
the index first: is it the length, or one past what you meant?
Pass all five tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each exercise is checked in your browser. Lists print differently
on this page than in Node's terminal, so the checks look at the
items and the length rather than at a printed list.
TypeScript refuses this program. Fix the one item that breaks the
promise of number[], so the program prints 35.
Loading the editor…
Exercise · Fix the error
Print the last day
This program should print the last day, Thu, but it prints
undefined. Change the index, and nothing else.
Loading the editor…
Exercise · Write the code
Fill an empty list
Make an empty list called pages that will only take numbers,
with its type written. Add 12, 40 and 7 to it with push, in
that order. Then print how many items it holds, and on the next
line the last one. The program prints 3, then 7.
Loading the editor…
Exercise · Predict the result
The type of the last estimate
Hover over last in VS Code. Which type does it show?
ts
const estimates: number[] = [15, 30, 5];const last = estimates.at(-1);
Recap
Recap · 3 questions
Check yourself
What type does TypeScript give const done = [true, false]?
Check yourself
tasks holds four items. Which reads the last one?
Check yourself
Can you push to a list in a const box?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Arrays and the T[] type
What things are
Word
What it means
Array
One value holding a list of values, in order
Item
One value in the list; also called an element
Index
An item's place, counted from 0
string[]
The type of a list of strings
T[]
A list whose items all have the type T
Code
Write
To
["buy milk", "call mom"]
Make a list of two strings
const tasks: string[] = [];
Make an empty list of strings
tasks[0]
Read the first item
tasks.length
Count the items
tasks[tasks.length - 1]
Read the last item
tasks.at(-1)
The last item, or undefined
tasks.push("pay rent")
Add an item at the end
tasks[1] = "call dad";
Put a new value at index 1
Rules
Rule
What it means
Count from 0
A list of 3 has items at 0, 1 and 2
Past the end
tasks[3] gives undefined, with no error
Brackets trust you
tasks[3] says string, even past the end
.at() admits it
Its type says undefined too
const locks the box
push is fine; a new list is TS2588
Empty list, write it
[] says nothing about what goes in
Where to go next
You can now keep many values in one array, read any of them by
its index, find the last one without running past the end, and
read and write the type of a list. TaskKit keeps every task it
adds, and its count comes from the list instead of a box kept up
by hand.
Next is for, for...of, and while. So far you have read
items one line at a time, an index per line. There you write the
lines once and let the program walk through every item of a list,
however long it is.
Before you move on, open index.ts, say which type added has on
the line const added = tasks.length;, then hover over it to see.
Then change the push to tasks.push(5), run
npx tsc --noEmit--types node index.ts, read the error, and put
it back.