Write your first generic function: give a function its own slot with <T>, let each call fill it from its arguments, and see why T keeps the type where any loses it. TaskKit gets findBy, a helper that searches any Map by a rule, tested on a Map of tasks and a Map of numbers.
TypeScript
Fundamentals
Your first generic function. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
At a theatre cloakroom you hand your coat over the counter and get a
numbered ticket. After the show you give the ticket back, and your
coat comes back to you: not somebody's umbrella, not a bag. The
person behind the counter takes coats, umbrellas and bags all
evening and works the same way with each. What comes back is what
you handed in, whatever it was.
In the last lesson TaskKit moved its tasks into a Map<string, Task>,
and get finds a task by its title in one step. Some questions are
not about a title, though: which task is number 2? This lesson writes
a function that searches a Map by any rule you give it, and then
gives that function a slot of its own, <T>, so it serves every Map
the way the cloakroom serves every coat: what comes back has the type
of what went in. By the end you can write a function like that and
say what fills its slot at each call, and TaskKit has findBy,
tested on two kinds of Map.
A Map has no find
A list has find (lesson 4.3): give it a rule, and it gives back the
first item the rule says true to. A Map does not. Ask TaskKit's Map
for task #2, the one whose id (identifier, the task's number) is 2,
the way you would ask a list, tasks.find((task) => task.id === 2),
and TypeScript refuses it. Its first error is Property 'find' does not exist on type 'Map<string, Task>'.; its second is about the
rule's task, which gets no type, because it was a list's find
that gave it one (lesson 4.3). A Map finds by key, with get, and by
nothing else.
You can write the search yourself. [...tasks.values()] collects the
Map's values into a list, as printList has done since lesson 10.1,
and that list has find. Put it in a function that takes the Map and
the rule:
It prints Call Mom. matches is a callback with the function type
of lesson 5.4: it takes a Task and gives back true or false.
When no task passes, find gives undefined, which is why the
function says Task | undefined.
One function with a slot
Lesson 6.10 counted chores in a Map<string, number>, the tally. Ask
the tally a question of the same kind: is any chore counted more than
once? The search is the same line; only the types around it change:
Only the types differts
function findCount( tally: Map<string, number>, matches: (count: number) => boolean): number | undefined { return [...tally.values()].find(matches);}
A copy for every kind of Map is the problem lesson 10.1 began with: a
description for lists of strings, another for lists of tasks, each the
same but for one type. The way out is the same too, one description
with a slot:
One description with a slotts
function findBy<T>( items: Map<string, T>, matches: (item: T) => boolean): T | undefined { return [...items.values()].find(matches);}
The <T> right after the function's name declares a type
parameter, as in lesson 10.1: a slot named T, like the one in
Array<T>, but this one belongs to the function. Every other T in
it uses that slot: the Map holds T values, the rule takes one T,
and the function gives back a T or undefined. A function with a
slot like this is a generic function. The parameters are now
items and item, because the function no longer knows what they
hold.
When you call it, the slot is filled, and every T becomes the type
that filled it. This is the type machine of lesson 10.1 again, now
for a function you wrote: findBy<T> goes in, the call fills the
slot with Task, and each part of the description comes out filled.
Press Next to send the parts through, or let it play:
findBy<T>
items: Map<string, T>
matches: (item: T) => boolean
gives back: T | undefined
T = Task, from tasks
findBy<Task>
items: Map<string, Task>changed
matches: (item: Task) => booleanchanged
gives back: Task | undefinedchanged
findBy(tasks, …) fills the slot: every T becomes Task
All 3 fields shown.Field 1 of 3: items comes out with a new type (Map<string, T> → Map<string, Task>)Field 2 of 3: matches comes out with a new type ((item: T) => boolean → (item: Task) => boolean)Field 3 of 3: gives back comes out with a new type (T | undefined → Task | undefined)
All 3 fields shown.
Each call fills the slot
The call never says Task, so where does it come from? TypeScript
reads the arguments. tasks is a Map<string, Task>, the parameter
says Map<string, T>, and the two match only if T is Task.
Lesson 5.1 said TypeScript cannot infer a parameter's type, because
its value only arrives with a call. A type parameter is different: it
is filled at every call, from what that call passes in. And it is
filled once per call: every T in that call is the same type.
It prints Call Mom, then 2: some chore was done twice. Paste it
into a file in VS Code (Visual Studio Code, your editor) and hover
findBy: the first call says findBy<Task>, the second
findBy<number>. The two calls, side by side: the machine above
showed the first column, and the second is the same function with
another type.
findBy(tasks, …)findBy(tally, …)T is
Task
From tasks
number
From tally
The rule's item
Task
task.id is checked
number
count > 1 is checked
The call gives
Task|undefined
number|undefined
One findBy, two calls: each fills T with its own type
The rule needs no type written, just as an arrow function handed to
a list's find takes its type from the list (lesson 4.3).
You can also fill the slot yourself, in angle brackets after the
name, as you did for new Map<string, Task>():
findBy<Task>(tasks, (task) => task.id === 2). TypeScript would
fill in Task anyway; what writing it adds is a check. Write
findBy<number>(tasks, …) and the call is refused; the first error
says Argument of type 'Map<string, Task>' is not assignable to parameter of type 'Map<string, number>'.
Why not any
There is a shorter way to make one function take every Map: any,
the escape hatch of lesson 8.5.
Bad — the values' type is any, so
a typo in the result passes the check and prints undefined.
Both functions take every Map, but only findBy remembers what the
Map held.
findAny gives back any, and whatever you read from any is any
too, so titel goes through unchecked. findBy gives back a
Task | undefined, and TypeScript refuses the typo with
Property 'titel' does not exist on type 'Task'. Did you mean 'title'?
TaskKit: findBy
Now TaskKit's step. No command calls findBy yet: every run starts
with an empty Map, so a command could only find what it had just
added. So findBy goes into tasks.ts with the other small helpers,
as TaskKit's first generic function, and two tests check it on two
kinds of Map every time you run the tests.
1
Add findBy to tasks.ts
In tasks.ts in ~/projects/taskkit, add this function at the end
of the file, after alphabetical:
tasks.tsts
export function findBy<T>( items: Map<string, T>, matches: (item: T) => boolean): T | undefined { return [...items.values()].find(matches);}
2
Test it on two kinds of Map
In tasks.test.ts, add findBy to the line that imports from
./tasks.ts, and import the type Task under it:
tasks.test.tsts
import { capitalize, percentFull, alphabetical, findBy } from "./tasks.ts";import type { Task } from "./tasks.ts";
Then add two tests at the end of the file, one on a Map of tasks and
one on a Map of numbers:
tasks.test.tsts
test("findBy finds task #2 in a Map of tasks", () => { const tasks = new Map<string, Task>(); tasks.set("pay rent", { id: 1, title: "Pay rent", status: "todo" }); tasks.set("call mom", { id: 2, title: "Call Mom", status: "todo" }); assert.equal(findBy(tasks, (task) => task.id === 2)?.title, "Call Mom");});test("findBy finds a count in a Map of numbers", () => { const tally = new Map<string, number>(); tally.set("water", 1); tally.set("milk", 2); assert.equal(findBy(tally, (count) => count > 1), 2);});
3
Check and run the tests
Run both scripts with npm (Node package manager, the tool that
installs packages and runs the project's scripts):
bash
npm run checknpm test
The check prints only its two > lines. The tests end like this:
The end of what npm test printstext
✔ findBy finds task #2 in a Map of tasks (0.07325ms)✔ findBy finds a count in a Map of numbers (0.056125ms)✔ a blank line is not a task left (0.363625ms)ℹ tests 10ℹ suites 0ℹ pass 10ℹ fail 0ℹ cancelled 0ℹ skipped 0ℹ todo 0ℹ duration_ms 103.240417
The numbers in brackets are how long each test took, in ms
(milliseconds, thousandths of a second), and duration_ms is the
whole run; they differ on every run.
Predict the type
The rule's parameter has no type written, so it takes one from the
slot. Here the Map's values are Status, the union TaskKit has used
since lesson 7.2.
Predict
What type does TypeScript give status, inside the rule?
ts
type Status = "todo" | "done";function findBy<T>( items: Map<string, T>, matches: (item: T) => boolean): T | undefined { return [...items.values()].find(matches);}const board = new Map<string, Status>();board.set("pay rent", "done");board.set("buy milk", "todo");const finished = findBy(board, (status) => status === "done");console.log(finished);
The common mistake: a T nobody declared
The Ts in the parameters are the ones you look at, so the <T>
after the name is the one you forget.
Common mistake
A generic function without its <T>
In tasks.ts, findBy is written without the slot after its name:
tasks.tsts
export function findBy( items: Map<string, T>, matches: (item: T) => boolean): T | undefined { return [...items.values()].find(matches);}
npm run check prints its two > lines, and then one error for
every T, each with the error code TS2304 (TS for TypeScript, then
the number of the error):
What the check printstext
tasks.ts:19:22 - error TS2304: Cannot find name 'T'.19 items: Map<string, T>, ~tasks.ts:20:19 - error TS2304: Cannot find name 'T'.20 matches: (item: T) => boolean ~tasks.ts:21:4 - error TS2304: Cannot find name 'T'.21 ): T | undefined { ~Found 3 errors in the same file, starting at: tasks.ts:19
Cannot find name 'T'.
The fix
Declare the slot right after the function's name:
tasks.tsts
export function findBy<T>(
Without <T>, the letter is just a name, and TypeScript looks for a
type called T the way it looks for Task: an interface or a
type somewhere in your files. There is none. When the same
Cannot find name comes once for every T, look at the line with
the function's name first.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each one is checked in your browser. Try it before you open the
hints; they come one at a time.
Exercise · Read the code
What the call gives back
findBy is the function from this lesson. In this call, what type
does TypeScript give long?
ts
const minutes = new Map<string, number>();minutes.set("pay rent", 10);minutes.set("call mom", 25);const long = findBy(minutes, (time) => time > 20);
Exercise · Fix the error
From strings to every type
firstOf was written for lists of strings, so TypeScript refuses the
call with a list of numbers. Give it a slot, so it takes a list of
any type and the program prints milk, then 30.
Loading the editor…
Exercise · Write the code
Count what passes
Write countBy: like findBy, it takes a Map and a rule, but it
gives back how many values pass the rule. The program should print
2, then 1.
Loading the editor…
Exercise · Read the code
One slot, one type
Here is another generic function. It puts two values in a new list.
Which call does TypeScript refuse?
ts
function pairOf<T>(first: T, second: T): T[] { return [first, second];}
Recap
Recap · 3 questions
Check yourself
What does the <T> after a function's name do?
Check yourself
What happens with findBy<number>(tasks, …)?
Check yourself
Why write findBy<T> rather than one findAny with any?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Your first generic function
What things are
Word
What it means
Generic function
A function with a slot: one function, many types
A function's slot
Its type parameter, filled at every call
Code
Write
To
function findBy<T>(…)
Declare a slot named T
items: Map<string, T>
Take a Map whose values fill the slot
findBy(tasks, …)
Call it; TypeScript fills T from tasks
findBy<Task>(tasks, …)
Fill the slot yourself
Rules
Rule
What it means
Declare it first
T without <T> is TS2304: Cannot find name
One slot, one type
Every T in one call is the same type
T, not any
any checks nothing; T keeps the type
A Map has no find
Search [...items.values()] instead
Module 10 on one page
Cheat sheet
Module 10: Reading Generic Types
What <T> means: Array<T> and Map<K, V>
Word or code
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
Slot names by habit: type, key, value
Array<string>
string[] the long way: the same type
Map<string, Task>
Text keys, a Task under each
new Map<string, Task>()
An empty Map with both slots filled
new Map() alone
Map<any, any>: write the types
Your first generic function
Word or code
What it means
function findBy<T>(…)
A function with a slot of its own
findBy(tasks, …)
The call fills T from its argument
findBy<Task>(tasks, …)
The slot, filled by you
T without <T>
TS2304: Cannot find name 'T'
T, not any
T keeps the type that went in
Where to go next
You can now write a function with a slot of its own: <T> after its
name, T wherever the type would go, and every call fills it from
its arguments. With the last lesson, that is Module 10: you read the
angle brackets in TypeScript's types and write them in your own.
TaskKit has findBy, tested on a Map of tasks and a Map of numbers.
Next is What asynchronous code is and why it exists, the start of
Module 11, where TaskKit learns to wait before it prints. Its types
have slots too: Promise<T>, later in that module, reads the way
Array<T> does.
Before you move on, open tasks.test.ts in VS Code. For each of the
two new tests, say what fills T in its findBy call, then hover
findBy to check. The hover starts with (alias) because the name
came in with an import; the slot is what follows findBy.