Learn to read types with angle brackets: one description with an empty slot serves every type, Array<T> fills one slot and Map<K, V> two, in order. See why an empty new Map() checks nothing, and move TaskKit’s tasks into a Map<string, Task> that catches a repeated title by itself.
TypeScript
Fundamentals
What `<T>` means: `Array<T>` and `Map<K, V>`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
In the hall cupboard stand three plastic storage tubs from the same
shop.
They are the same size, and each has a small label window on the
front for a paper label: "Socks", "Screws", "Cables". The shop sold
one kind of tub; you chose what goes in it and wrote it in the
window. And the label is what you read before you open the lid:
reach into "Screws", and you know what your hand will find.
TypeScript has types like that, and you have used them for a while.
You have written string[] since Module 4, Task[] since Module 6
and new Map<string, number>() since lesson 6.10, which asked you to
read the types in angle brackets "as you read string[]". This lesson
says what they are. Hover push in tasks.push( in TaskKit's
index.ts, in VS Code (Visual Studio Code, your editor), and it says
(method) Array<Task>.push(...items: Task[]): number. The (method)
means push is a function that belongs to the list, and the <Task>
after Array is the paper label in the tub's window. By the end you
can read any type with angle brackets and say what each type in them
stands for, and TaskKit keeps its tasks in a Map<string, Task> that
notices a repeated title by itself.
One description, an empty slot
A list of strings and a list of tasks do the same things. Both have
a length, both take push, both give an item back from at(0).
Only the kind of item differs. TypeScript could keep a separate
description for each kind: a list of strings, a list of numbers, a
list of tasks, each repeating the same methods with another type
in them. Instead it keeps one, written with an empty slot.
That description is called Array<T>. The T between the angle
brackets is the slot's name: a type parameter, a placeholder for a
type nobody has chosen yet. A type with a slot like that is a
generic type: generic, because one description serves every
kind of item. When you use it, you put a type in the slot, as in
Array<Task>, and the type you put there is the type argument.
The two names come from lesson 5.1: a function's parameter waits for
a value and the argument is the value you pass; a type parameter
waits for a type, and the type argument is the type you pass.
Task[] is the same type, written the short way. Array<string>
and string[] are one type with two spellings, and VS Code writes
the long one back as the short one: hover items in
const items: Array<string> = ["milk", "tea"];, and it says
const items: string[].
Filling the slot changes the whole description at once: every T in
it becomes the type you chose. The figure below is a type machine,
a picture this course uses for types: what goes in comes first, then
what works on it, then what comes out. Here a list's description goes
in, Task fills the slot, and each line comes out with the type you
get. Press Next to send the lines through one by one, or let it
play:
Array<T>
[0]: T
at(0): T | undefined
filter(…): T[]
length: number
T = Task
Array<Task>
[0]: Taskchanged
at(0): Task | undefinedchanged
filter(…): Task[]changed
length: number
Fill the slot, and every T in the description becomes Task
All 4 fields shown.Field 1 of 4: [0] comes out with a new type (T → Task)Field 2 of 4: at(0) comes out with a new type (T | undefined → Task | undefined)Field 3 of 4: filter(…) comes out with a new type (T[] → Task[])Field 4 of 4: length passes through unchanged
All 4 fields shown.
length holds no T, so it comes out as it went in: a list of
anything counts its items with a number. Fill the slot with string
instead (T = string), and the same four lines come out as string,
string | undefined, string[] and number.
The machine filled the slot once. Run three lists, to see it filled
three ways, one type for each list:
It prints milk 30 Pay rent. In VS Code, hover each at: the
hover names the filled type before the dot, Array<string>.at on
the first and Array<Task>.at on the last.
Where the T is written
The description lives in .d.ts files (declaration files: they hold
types for TypeScript and no code for Node), like the ones lesson 9.3
installed for packages. TypeScript brings its own for what is built
into JavaScript, lists and Maps included. Hover the word Array in
Array<string>, and VS Code says interface Array<T>. Here are a
few of its lines, gathered from TypeScript 7's own files:
It is an interface, as in lesson 6.4, with <T> after its name:
the slot. Read the lines with that in mind. length is a number.
push takes any number of items, each a T (the rest parameter of
lesson 5.3), and gives back a number, the list's new length. at
gives back a T, or undefined past the end. When you write
tasks.push(…) on a Task[], TypeScript reads this description
with Task in every T, and that is the hover you saw at the
start: (method) Array<Task>.push(...items: Task[]): number.
A package's .d.ts in node_modules reads the same way: find the
slots after the name, then look for the same letters in the lines.
TaskKit has one at hand. Open node_modules/boxen/index.d.ts, and
near the top is export type Color = LiteralUnion<. LiteralUnion is
a type with two slots, and this line fills both of them: with the
names of the colors boxen knows, and with string. Color is the
name the filled type gets.
Two slots: Map<K, V>
A Map needs two types: one for its keys, one for its values. So its
description has two slots, with a comma between them: Map<K, V>.
K stands for the keys and V for the values, and they are filled
in that order: in Map<string, number>, string goes into K and
number into V. Here are a few of its lines:
This is why lesson 6.10's tally.get("milk") was
number | undefined: the description says V | undefined, and
tally put number in V. The same two slots, filled for the
Map you know and for the one TaskKit gets in this lesson:
Map<string, number>Map<string, Task>K, the keys
string
Chores: "water", "milk"
string
Titles: "pay rent"
V, the values
number
How many times: 2
Task
The whole task
get(key) gives
number|undefined
Task|undefined
K is the type of every key, V the type of every value
Hover get on a Map<string, Task>, and VS Code says
(method) Map<string, Task>.get(key: string): Task | undefined.
The letters are names, like a parameter's name. TypeScript's own files
chose T for type, K for key and V for value, and most code
follows the habit. The Set of lesson 6.10 has one slot,
Set<T>. Record has two, keys first, but its own description
calls the second one T rather than V. The letter tells you
nothing by itself; the place does. The first type in the brackets
of a Map or a Record is always the keys' type.
When you fill the slot yourself
TypeScript fills a slot by itself when it can see values:
["milk", "tea"] is a string[], and lesson 6.10's
new Set(notes) came out a Set<string>. An empty new Map()
gives it nothing to look at. Hover tasks in
const tasks = new Map();, and VS Code says
const tasks: Map<any, any>. Both slots hold any, the escape
hatch of lesson 8.5, which checks nothing.
Bad — an empty Map with no types,
so a task goes in under its id (identifier, the task's number) and is
looked up by its title.
K is string now, so TypeScript refuses the number rent.id with
Argument of type 'number' is not assignable to parameter of type 'string'. Use the title in lower case, "pay rent", as the key,
and the program runs:
The first version passed the check and printed undefined: the task
went in under the number 1, get looked for the text "pay rent",
found nothing, and nothing said so. It is lesson 4.1's rule for an
empty list again: when you start empty, write the type.
TaskKit: tasks kept in a Map
Now TaskKit's step. Its tasks sit in a list, and every new title is
compared with every title in it, through sameTask, to catch a
repeat. A Map can do that job by itself. Keep each task under its
title in lower case, and "Pay rent" and "pay rent" share one key:
asking whether a title is there is one get.
1
Make the list a Map
In index.ts in ~/projects/taskkit, replace
const tasks: Task[] = []; with this line:
index.tsts
const tasks = new Map<string, Task>();
The keys are titles in lower case; each value is the whole task.
2
Look the title up
In the add case, replace the two lines that start
const titles = and const twin = with these two:
twin is now a Task | undefined, no longer a title. Inside
else if (twin !== undefined) it is a Task, so change the line
under it to print the title of the task that is already there:
index.tsts
console.log("Already on the list:", twin.title);
3
Count with size, add with set
A Map has no length; it counts with size (lesson 6.10). Change
tasks.length to tasks.size in the three places outside the push
line, which is replaced next: else if (tasks.size < limit),
if (tasks.size === 0) and printSummary(tasks.size, limit);. Then
replace the tasks.push line with this set:
sameTask has no job left. Take it out of the import line, so it
reads import { capitalize } from "./tasks.ts";, and delete the
function from tasks.ts.
4
Let printList take the Map
In print.ts, change the first lines of printList to these:
print.tsts
export function printList(tasks: Map<string, Task>): void { const byName = [...tasks.values()].toSorted((a, b) => alphabetical(a.title, b.title) );
The parameter's type fills both slots, the same Map<string, Task>
as tasks in index.ts. A Map's values() hands out its values one
after another, here every Task; the spread of lesson 6.8 collects
them into a new list, as [...new Set(notes)] did in lesson 6.10.
toSorted then sorts that list as before.
5
Check, run TaskKit, run the tests
Run the three scripts with npm (Node package manager, the tool that
installs packages and runs the project's scripts):
bash
npm run checknpm start add "pay rent" "call Mom" "Pay rent" "buy milk"npm test
The check prints only its two > lines. TaskKit prints:
What TaskKit printstext
> start> node index.ts add pay rent call Mom Pay rent buy milk┌ TaskKit 0.1 ───────────────┐│Your tasks, in your terminal│└────────────────────────────┘Added: Pay rentAdded: Call MomAlready on the list: Pay rentAdded: Buy milk3 tasks added, room for 2 moreList 60% fullYour list, A to Z:#3 [todo] Buy milk, due: not set#2 [todo] Call Mom, due: not set#1 [todo] Pay rent, due: not set
The second "Pay rent" found its key and was not added again. The
tests still pass, the same eight as before: none of them tested
sameTask. They end like this; the numbers in brackets and
duration_ms are times in ms (milliseconds, thousandths of a second),
and they differ on every run:
The end of what npm test printstext
✔ a blank line is not a task left (0.385917ms)ℹ tests 8ℹ suites 0ℹ pass 8ℹ fail 0ℹ cancelled 0ℹ skipped 0ℹ todo 0ℹ duration_ms 94.223458
Predict the type
A slot can hold any type, a whole list included. Read this Map's
two types, and decide what get gives back before you run it.
You think "a Map of tasks", and the type you write says only that.
Common mistake
A Map written with one type
In print.ts, the parameter of printList gets one type in its
brackets:
print.tsts
export function printList(tasks: Map<Task>): void {
npm run check prints its two > lines, and then this. The message
starts with its error code, TS2314 (TS for TypeScript, then the
number of the error), and its first line is one long line in your
terminal, broken here to fit:
What the check printstext
print.ts:6:34 - error TS2314: Generic type 'Map<K, V>' requires 2type argument(s).6 export function printList(tasks: Map<Task>): void { ~~~~~~~~~Found 1 error in print.ts:6
Generic type 'Map<K, V>' requires 2 type argument(s).
The fix
Fill both slots, keys first:
print.tsts
export function printList(tasks: Map<string, Task>): void {
The message writes the description's slots out for you:
Map<K, V>, two letters, so two types. Count them, then ask what
each stands for. The order matters as much as the count:
write new Map<Task, string>() in index.ts, and tasks.get(key)
is refused at once, because key is a string, and this Map's keys
must be a Task.
countItems prints how many chores each day holds, but TypeScript
refuses its first line: the parameter has no type. The Map's type is
on its own line below; the parameter must say the same thing. Write
the type, so the program prints Monday: 2 and then Friday: 1.
Loading the editor…
Recap
Recap · 3 questions
Check yourself
In Array<T>, what is T?
Check yourself
You write Map<Task> for a Map of tasks. What happens?
Check yourself
What type does const tasks = new Map() give tasks?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
What <T> means: Array<T> and Map<K, V>
What things are
Word
What it means
Generic type
A type with a slot: one description, many types
Type parameter
The slot's name, such as T
Type argument
The type you put in the slot
T, K, V
Names by habit: type, key, value
Array<T>
A list's description, its slot still empty
Map<K, V>
A Map's description: keys first, values second
Code
Write
To
Array<string>
Say string[] the long way: the same type
Map<string, Task>
Text keys, a Task under each
new Map<string, Task>()
Make an empty Map with both slots filled
Set<string>
Name a Set of strings: one slot
[...tasks.values()]
Get a Map's values as a list
Rules
Rule
What it means
Every T
Filling the slot changes every T in the description
The place counts
The first type of a Map is the keys' type
Empty, write it
new Map() alone is Map<any, any>
Count the slots
TS2314 names them: Map<K, V> takes two
Read the hover
Array<Task>.push: the filled type before the dot
Where to go next
You can now read a type with angle brackets: find its slots, say
what fills each one, and find the same letters in the lines of its
description. TaskKit keeps its tasks in a Map<string, Task>, and
a repeated title is caught by one get.
Next is Your first generic function. So far the slots were in
TypeScript's own descriptions; there you write a function with a
slot of its own, and TaskKit gets findBy, a helper built that
way.
Before you move on, open TaskKit in VS Code and hover three things:
tasks in index.ts, get in tasks.get(key), and toSorted in
print.ts. For each, say out loud what fills every slot.