Hand a function over without calling it: keep it in a box, give your own named function to filter, and write a function that takes one and calls it back. See countIf call isCall once for every task, read a function type such as (task: string) => boolean, and learn what TypeScript says when a callback is called instead of handed over.
TypeScript
Fundamentals
Functions as values: callbacks and function types. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
Sunday, and the pancake card is out of the drawer again. This time
you are not at the stove: your friend is, and you have a train to
catch. You do not make the pancakes for them before you go. You
hand over the card, and they follow it when it is their turn to
cook. The card is something you can pass from hand to hand; the
pancakes are what you get by following it.
Your functions are cards too. Until now you have mostly followed
them, by calling them: left(25), plan("call mom"). But every
arrow you handed to filter, toSorted or reduce in Module 4 was
a card handed over: you did not call it, the method did, once for
every item. In this lesson you hand over your own named functions
the same way, write a function of your own that takes one, and
write the type that says which functions fit. By the end you will
have one counting function that counts any kind of task you
describe to it.
A function is a value
Here is a function that answers one question about a task: is it a
phone call?
ts
function isCall(task: string): boolean { return task.startsWith("call");}
Up to now, its name has always come with parentheses:
isCall("call mom"). The parentheses are what run it. Without
them, isCall is still a name, and it still means something: the
function itself, the card rather than the pancakes. A function is a
value, like 5 or "buy milk": you can put it in a box, and
hand it to another function, without running it.
construle = isCall;
(task: string) => boolean
isCall: the function itself
Does: Hands the function over; its body has not run
Never: It is never true or false: it is the function
constmatch = isCall("call mom");
match: boolean
isCall("call mom"): its answer
Does: Runs the body now, and keeps what it gives back
Never: It never holds the function itself: only true
Without parentheses, the function; with them, its answer
The green notes are what VS Code (Visual Studio Code, your editor)
shows when you hover over each box. match holds a boolean, the
answer of one call. rule holds a type you met once, in lesson
4.4's sorting error, written here for isCall:
(task: string) => boolean: a function that takes a string and
gives back a boolean. That is the type of isCall itself, and the
last section of this lesson reads it piece by piece.
A box that holds a function can be called like the function, with
parentheses after the box's name. Run it:
It prints true, then [Function: isCall], then false. The
second line is Node telling you it was handed a function, named
isCall, and did not run it. On the third, rule and isCall are
two names for one function, so rule("buy milk") runs the body of
isCall. Lesson 5.2 kept an arrow in a box; this is the same thing
done with a declaration.
Your own function, handed to a method
In lesson 4.3 you handed filter a rule written right where it
was needed: (task) => task.startsWith("call"). That rule is the
body of isCall, written a second time. Now that isCall exists,
hand filter the function itself:
calls.tsts
function isCall(task: string): boolean { return task.startsWith("call");}const today = ["call mom", "buy milk", "call the bank"];console.log(today.filter(isCall));console.log(today.filter((task) => isCall(task)));
Both lines print [ 'call mom', 'call the bank' ]. The second
hands filter an arrow whose only job is to call isCall; the
first hands over isCall and skips the extra step in the middle. Notice that
nothing in today.filter(isCall) calls isCall. filter does,
once for every item, exactly as it called your arrows in lesson
4.3.
A function you hand to another function, for that function to call
when it needs to, is called a callback: you give it over, and it
is called back later, from inside. Every rule you gave map,
filter, find, toSorted and reduce in Module 4 was a
callback. What is new is that the callback can be a function with a
name, declared once at the top of your file and handed to as many
methods as you like.
A function that takes a function
filter takes a callback because the people who wrote it could not
know what you would want to keep. You meet the same problem in your
own code the moment two functions do the same work with one detail
different.
Bad — two functions that differ in
one word; a third kind of task means a third copy of the loop.
ts
function countCalls(tasks: string[]): number { let count = 0; for (const task of tasks) { if (task.startsWith("call")) { count += 1; } } return count;}function countBuys(tasks: string[]): number { let count = 0; for (const task of tasks) { if (task.startsWith("buy")) { count += 1; } } return count;}const today = ["call mom", "buy milk", "call the bank"];console.log(countCalls(today));console.log(countBuys(today));
Good — one loop; the question it
asks about each task is handed in.
ts
function isCall(task: string): boolean { return task.startsWith("call");}function isBuy(task: string): boolean { return task.startsWith("buy");}function countIf( tasks: string[], rule: (task: string) => boolean): number { let count = 0; for (const task of tasks) { if (rule(task)) { count += 1; } } return count;}const today = ["call mom", "buy milk", "call the bank"];console.log(countIf(today, isCall));console.log(countIf(today, isBuy));
Both print 2 and 1. In the first, the loop is written twice,
and a mistake in it has to be found and fixed twice. In the second,
countIf has a second parameter, rule, whose type is the one you
met on the hover: a function that takes a string and gives back a
boolean. Inside, rule(task) calls whatever function the call
handed over. countIf does not know or care which one it is.
Here is the second program, cut to the call that counts calls.
Press Next step to follow it one step at a time, or Play:
CodeThe program, line by line. The marked line is the one the computer is running now; the lines above it have run.ts
ts
function isCall(task: string): boolean { return task.startsWith("call");}function countIf( tasks: string[], rule: (task: string) => boolean): number { let count = 0; for (const task of tasks) { if (rule(task)) { count += 1; } } return count;}const today = ["call mom", "buy milk", "call the bank"];console.log(countIf(today, isCall));
MemoryThe boxes in memory, each with its name. A box appears when a line makes it; the one just filled or changed is orange.
ruleisCallisCall
count00
task"call the bank""call the bank"
OutputEverything the program has printed so far.
Nothing printed yetNothing printed yet
Every step as text
Line 17.
Line 17 calls countIf with two arguments: the list, and
isCall with no parentheses. Nothing has been called but
countIf.
Line 8.rule = isCall, count = 0. Inside countIf.
The call filled both parameters: tasks holds the list, and the
box rule holds the function isCall itself.
The second task. isCall gives back false, and count stays
at 1.
Line 2.rule = isCall, count = 1, task = "call the bank". Inside countIf → isCall.
The third task. isCall gives back true again.
Line 11.rule = isCall, count = 2, task = "call the bank". Inside countIf.
count goes up to 2. The loop has no tasks left.
Line 17.
return handed 2 back to line 17, and it is printed. isCall ran
three times, and every call came from countIf.
Prints 2
countIf calls rule for every task, and rule is isCall
Inside countIf the function is called rule, the way in lesson
5.1 every value a call brings is called by its parameter's name.
Each answer went back to countIf, and countIf decided what to
do with it: your line never saw them.
Now press Step on the same program. While the computer is
inside isCall, the Call stack column says
global › countIf › isCall: your file called countIf, and
countIf called the function you gave it.
count.tsts
function isCall(task: string): boolean { return task.startsWith("call");}function countIf( tasks: string[], rule: (task: string) => boolean): number { let count = 0; for (const task of tasks) { if (rule(task)) { count += 1; } } return count;}const today = ["call mom", "buy milk", "call the bank"];console.log(countIf(today, isCall));
Reading a function type
Every parameter in lesson 5.1 had its type written, because nothing
else could say what a call would bring. rule is no different. It
takes a function, so its type is a function type: a description
of what a function must take and what it must give back.
(task: string) => boolean says it in two halves. The parentheses
hold the parameters, written as in any function. After the arrow
comes the type the function gives back.
That arrow is the one from lesson 5.2, used in a new place, and it
is easy to read the two as one. Put them side by side:
function countIf( tasks: string[], rule: (task: string) => boolean): number {
Then: the type it gives back
A function type: what goes in, what comes out
Does: Says what a function must take and give back
Never: Its return type comes after a colon, never after =>
In a type, => points at a type; in a function, at the body
In the function type, => is followed by a type, boolean, and
nothing runs. In the arrow function, the return type sits after a
colon, : boolean, and => is followed by the body that does the
work. Read a function type aloud as "a function that takes a
string and gives back a boolean", and it reads as a description,
not as work to do.
The name inside the type, task, is only a label for the reader. It
has to be there, but any name will do: TypeScript checks the types and
their order, not the names, so a function whose parameter is called
item fits just as well. What it checks is the rest: every function
handed to rule has to take a string and give back a boolean.
So an arrow written right in the call needs no types of its own.
rule already says what will come in, so task is a string with
no type written, the way map gave your arrows their type in lesson
4.3. Run it:
count.tsts
function countIf( tasks: string[], rule: (task: string) => boolean): number { let count = 0; for (const task of tasks) { if (rule(task)) { count += 1; } } return count;}const today = ["call mom", "buy milk", "call the bank"];console.log(countIf(today, (task) => task.includes("milk")));console.log(countIf(today, (task) => task.length < 10));
It prints 1, for the one task with milk in it, and 2, for the
two tasks shorter than ten characters. Hand it
(task) => task.length instead, and TypeScript refuses it with
TS2322 (TS for TypeScript, then the number of this kind of
error): Type 'number' is not assignable to type 'boolean'. A
length is a number, and rule promised countIf a true or a
false. A declared function that gives back a number is refused
too, with TS2345 and a longer message that names both function
types. And a rule with no type at all is lesson 5.1's TS7006:
Parameter 'rule' implicitly has an 'any' type.
TaskKit's sorting rule gets a name
Now TaskKit's step for this lesson. It hands toSorted its rule as
an arrow written inside the call. Declared once as a function, the
rule gets a name that says what it does, and the call reads like a
sentence. That bends lesson 5.2's rule, which keeps a short rule
handed to a method as an arrow: a rule whose body says how
(a.localeCompare(b)) reads better with a name that says what
(alphabetical). Its type, (a: string, b: string) => number, is
exactly what toSorted wants.
Open index.ts in ~/projects/taskkit. At the top of the file,
under percentFull, declare the rule:
index.tsts
function percentFull(added: number, limit: number): number { // Rounded: without it, a limit of 3 prints 66.66666666666666 return Math.round((added / limit) * 100);}function alphabetical(a: string, b: string): number { return a.localeCompare(b);}const version = "0.1";
Near the end of the file, hand it to toSorted by its name, with no
parentheses after it: toSorted calls it, the way filter called
isCall earlier in this lesson.
index.tsts
const byName = tasks.toSorted((a, b) => a.localeCompare(b));const byName = tasks.toSorted(alphabetical);
Check the file with tsc (the TypeScript compiler, which npx
starts) and run it:
npx tsc prints nothing: the file passes. Then TaskKit prints:
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Added: Pay rentAdded: Call MomAdded: Buy milkTasks added: 3 of 5, room for 2 moreList 60% fullYour list, A to Z:1. Buy milk2. Call Mom3. Pay rent
The same list, A to Z. The rule did not change, only where it is
written.
Predict before you run
A function can call its callback more than once, and can hand one
answer straight back to the next call. Follow the inner call first:
its answer is what the outer call is given.
Since your first console.log(…), a function's name has come with
parentheses. So the hand reaches for them by itself, even where the
parentheses do exactly the wrong thing.
Common mistake
Calling the callback where it should be handed over
You want countIf to count the calls, and you hand it isCall
the way a function is usually written, with parentheses:
count.tsts
function isCall(task: string): boolean { return task.startsWith("call");}function countIf( tasks: string[], rule: (task: string) => boolean): number { let count = 0; for (const task of tasks) { if (rule(task)) { count += 1; } } return count;}const today = ["call mom", "buy milk"];console.log(countIf(today, isCall()));
npx tsc --noEmit--types node count.ts refuses it, so you can fix
it before you run it:
Outputtext
count.ts:17:28 - error TS2554: Expected 1arguments, but got 0.17 console.log(countIf(today, isCall())); ~~~~~~ count.ts:1:17 - An argument for 'task' was not provided. 1 function isCall(task: string): boolean { ~~~~~~~~~~~~count.ts:17:28 - error TS2345: Argument of type'boolean' is not assignable to parameter of type'(task: string) => boolean'.17 console.log(countIf(today, isCall())); ~~~~~~~~Found 2 errors in the same file, starting at:count.ts:17
The long lines are one line each in your terminal, broken here to
fit the page.
Argument of type 'boolean' is not assignable to parameter of type '(task: string) => boolean'.
The fix
Hand the function over: its name, with no parentheses.
count.tsts
function isCall(task: string): boolean { return task.startsWith("call");}function countIf( tasks: string[], rule: (task: string) => boolean): number { let count = 0; for (const task of tasks) { if (rule(task)) { count += 1; } } return count;}const today = ["call mom", "buy milk"];console.log(countIf(today, isCall));
Read the second message: the argument is a boolean, and the
parameter wanted a function. isCall() ran isCall right there, on
line 17, and what reached countIf was its answer, the pancakes
instead of the card. The first message is the same mistake seen
from inside isCall: a call with no task. So when an error puts
boolean or string where a function type was wanted, look for
parentheses after the name you meant to hand over.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each one runs in your browser. Press Check when you think you
have it; if you are stuck, the hints come one at a time.
Exercise · Read the code
Hand filter your own function
What does this program print?
ts
function isLong(task: string): boolean { return task.length > 8;}const today = ["call mom", "pay the rent"];console.log(today.filter(isLong));
Exercise · Fix the error
Give back a boolean
This program should count the tasks longer than 8 characters and
print 1. TypeScript refuses the last line with TS2322:
Type 'number' is not assignable to type 'boolean'. Fix the arrow.
Loading the editor…
Exercise · Fix the error
Give rule its type
TypeScript refuses this program with Parameter 'rule' implicitly has an 'any' type., and says the same about task on the last
line: with no type on rule, nothing tells it what task will be.
Write the type of rule and nothing else, so that the program
prints 2.
Loading the editor…
Exercise · Write the code
Write labelAll
Write a function labelAll that takes a list of tasks and a
function that turns one task into a new text, and gives back a new
list with every task turned. Write the types of both parameters and
the return type. The lines that call it are already there; they
print [ 'BUY MILK', 'CALL MOM' ] and [ 'buy milk!', 'call mom!' ].
Loading the editor…
Recap
Recap · 3 questions
Check yourself
What does today.filter(isCall) hand to filter?
Check yourself
In countIf(today, isCall), who calls isCall?
Check yourself
What does (task: string) => boolean describe?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Functions as values: callbacks and function types
What things are
Word
What it means
Function as a value
Its name without parentheses: kept, or handed over
Callback
A function you hand over for another function to call
Function type
What a function takes and gives back
[Function: isCall]
What Node prints when handed a function itself
Code
Write
To
isCall
Name the function itself, without running it
isCall("call mom")
Run it now; its answer takes its place
const rule = isCall;
Keep a function in a box; call it rule(…)
today.filter(isCall)
Hand a method your own function
rule: (task: string) => boolean
Take a function as a parameter
rule(task)
Call the function you were given
Rules
Rule
What it means
Parentheses run it
Without them, the function is handed over
Called, not handed
isCall(): TS2554, then TS2345
=> in a type
Points at the type it gives back
Names in a type
Any name: (item: string) => boolean fits too
An arrow in place
The function type gives task its type
Wrong kind of answer
TS2322 for an arrow in place
No type on rule
TS7006, as for any parameter
Where to go next
You can now treat a function as a value: name it without calling
it, keep it in a box, and hand it to filter or to a function of
your own. You can write that function, call the callback it was
given, and write the parameter's function type, so TypeScript
checks every function handed to it. And you know the mistake to
look for when a boolean turns up where a function was wanted.
Next is Scope and closures (basics). Most functions you have
written so far use only their own parameters, but the rule TaskKit
hands find reads newTask, a box outside it. There you see which
boxes a function can reach from where it is written, and why that
rule works.
Before you move on, make this lesson's mistake in TaskKit: write
tasks.toSorted(alphabetical()), with parentheses, and run the
check. It reports the byName line twice: TS2554,
Expected 2 arguments, but got 0., and TS2345, with number
where (a: string, b: string) => number was wanted. Then take the
parentheses out and check again.