Let a call leave an argument out with an optional parameter and check it before use, give a parameter a default value that fills in when nothing comes, and take any number of arguments as one list with a rest parameter. See a call fill each box, learn the order parameters go in, and what TypeScript says when a call brings too few, too many, or the wrong order.
TypeScript
Fundamentals
Optional, default, and rest parameters. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
Your grandmother's pancake card is out of the drawer again. Under
Pancakes it says For: 4 people, and on a quiet Sunday nobody
tells you how many are coming, so you make it for four: the card
has a number for when nobody says. At the bottom, in pencil, it
says Add any fruit you have. One banana, three kinds of berries,
or none at all: the card works with any of them.
Your left from lesson 5.1 is stricter than that card. It takes
exactly one argument: left() is refused with
Expected 1 arguments, but got 0., and left(25, 40) with
Expected 1 arguments, but got 2. The functions that came with the
language are not that strict. sort() in lesson 4.4 takes a rule or
none at all, and console.log takes as many values as you give it. In
this lesson you write functions like those: a call that may leave an
argument out, a value to use when it does, and a parameter that takes
any number of arguments. By the end your own functions will be as easy
to call as theirs.
Calls that leave something out
Here is a function that writes one line of your day's plan:
Not every task has an estimate. You know buying milk takes 5
minutes; how long calling your mom takes, you have no idea. With
this first line, every call has to bring both. plan("call mom")
is refused with TS2554 (TS for TypeScript, then the number of
this kind of error): Expected 2 arguments, but got 1., lesson
5.1's error for a call that brings too few, and the only way through is
to make a number up.
A question mark after a parameter's name makes it an optional
parameter: one that a call may leave out.
ts
function plan(task: string, minutes?: number): string {
A call may now bring one argument or two. Three is still too many:
plan("pay rent", 10, 5) is refused with Expected 1-2 arguments, but got 3., where 1-2 is the range a call may bring.
Leaving it out has a price inside the body. When a call brings no
minutes, nothing is put in the box minutes, and lesson 3.3 gave
that nothing its name: undefined. So TypeScript gives minutes
the type number | undefined, a number or nothing, and the body has
to check before it uses it as a number, the way lesson 3.5 checked a
word that might not have been typed:
It prints buy milk: 5 min and then call mom. In the second
call, minutes holds undefined, the if is true, and return
hands back the task alone. Below the if, TypeScript knows
minutes is a number: the check took undefined away.
A value to use when nothing comes
Often a function does not want to do anything different when
nothing comes. It only wants the usual value. Most of your tasks
take about a quarter of an hour, so a plan with no minutes could
just say 15. Lesson 3.4 wrote that as estimate ?? 15. A parameter
can carry it itself:
ts
function plan(task: string, minutes = 15): string {
= 15 after the name gives the parameter a default value: the
value it gets when a call leaves it out. There is no type written,
and none is needed. Lesson 2.6's rule is back: a box that starts
with a value gets its type from it, and 15 is a number. Lesson
5.1 had you write every parameter's type because nothing came with
the parameter; a default comes with something.
Put this in a file in VS Code (Visual Studio Code, your editor) and
hover over minutes: it shows (parameter) minutes: number. This
course writes a default without a type from here on.
A parameter every call must bring, like those of lesson 5.1, is
required. Here are the three kinds side by side, each one with a call that
leaves minutes out:
function plan(task: string, minutes?: number): string {
minutes: number | undefined
Optional: minutes?
Does: A call may leave it out: plan("call mom")
Never: It is never sure to hold a number: check it first
function plan(task: string, minutes = 15): string {
minutes: number
With a default: minutes = 15
Does: Left out, it holds 15
Never: It never holds undefined inside the body
Leave minutes out: refused, undefined, or the default
An optional parameter may hold undefined, so every line that
needs a number from it has to check first: in arithmetic TypeScript
refuses it (TS18048), and in a template it quietly prints
undefined. A default is in the box before the body's first line
runs. Here is a program that calls it twice, once with minutes and once
without. 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
And the second. One function, one body, and the minutes came from
the call or from the default.
Prints call mom: 15 min
A left-out argument: the default fills the box, every call
Three things happened there. The call filled the parameters in
order, left to right, as in lesson 5.1: "buy milk" went in task
and 5 in minutes. The default was used only when the call
brought nothing for it. And the body never knew the difference. It read
minutes and found a number both times.
Now press Step on the same program and watch the Call stack
column say global › plan inside each call:
A default works much like ?? built into the parameter, with one
difference: ?? fills in for null and undefined, a default only
for undefined. A call that leaves the argument out gets it, and so
does a call that passes undefined itself.
Any number of arguments
Now add up a day. Monday has three tasks, Tuesday has five, and
Sunday has none. A function with a parameter for each argument
takes exactly that many, and no one number fits every day:
function total(first: number, second: number): number { return first + second;}total(25, 15, 30);
error TS2554
A parameter for each argument
Expected 2 arguments, but got 3.
function total(...minutes: number[]): number { return minutes.reduce((sum, minute) => sum + minute, 0);}total(25, 15, 30);
minutes: number[]
A rest parameter: all of them, in one list
Does: Takes any number of arguments, none included
Never: It is never anything but a list
Two parameters take two; a rest parameter takes them all
Three dots before the last parameter's name make it a rest
parameter: it takes the rest of the arguments, however many there
are, and hands them to the body as one array, in the order the call
wrote them. Its type is the type of that whole list, number[]
from lesson 4.1, not the type of one item. Inside, it is a list
like any other, so reduce from lesson 4.5 adds it up. Run it:
total.tsts
function total(...minutes: number[]): number { return minutes.reduce((sum, minute) => sum + minute, 0);}console.log(total(25, 15, 30));console.log(total(25));console.log(total());
It prints 70, 25 and 0. With no arguments at all, minutes
is an empty list, [], never undefined, so the body needs no
check. That is why lesson 4.5's start value matters:
reduce on an empty list hands back the start, 0. And
console.log, which takes any number of values, has been showing
you a rest parameter since your first lesson.
One thing a rest parameter does not take is a list you already
have. total(planned), where planned is [25, 15], is refused
with Argument of type 'number[]' is not assignable to parameter of type 'number'.: the function wants the numbers one by one.
Module 6 shows how to hand a list over as separate arguments, with
the same three dots.
Which parameter comes first
A call fills the parameters from the left, so their order in the
first line matters. The ones every call brings go first, then the
ones a call may leave out, and a rest parameter, which takes
whatever is left, goes last.
Bad — the optional parameter comes
first, so a short call would fill it and leave the required one
empty.
The first is refused with TS1016: A required parameter cannot follow an optional parameter. Picture the call plan("buy milk").
A call fills from the left, never by type, so "buy milk" would
land in minutes, and task, which every call must bring, would
get nothing. Putting the optional parameter last means that never
happens. The
second prints buy milk: 5 min.
A rest parameter has the same rule and its own message. Anywhere
but last, ...tasks: string[] is refused with TS1014: A rest parameter must be last in a parameter list.: it takes every argument that is
left, so nothing could ever reach a parameter after it.
Predict before you run
Lesson 3.4 showed that ?? keeps 0 and "", because they are
values and not nothing. This plan has a default. Decide what each
call puts in minutes, then say what the first line will be.
A ? is one character, and it makes the call shorter right away.
The body that uses the parameter is a few lines further down, and
it is easy to forget that it now has to cope with nothing.
Common mistake
Making a parameter optional and using it as if it were there
TaskKit's percentFull from lesson 5.1 is always called with the
limit, 5. You want to call it with the count alone, so you copy it
into a file percent.ts in ~/projects/taskkit, under its own name
percentOf (two functions with one name in one folder would clash),
and make limit optional:
percent.tsts
function percentOf( added: number, limit?: number): number { return Math.round((added / limit) * 100);}console.log(`List ${percentOf(3)}% full`);
npx tsc --noEmit--types node percent.ts (tsc is the TypeScript
compiler, which npx starts) refuses it:
The first line is one long line in your terminal, broken in two
here to fit the page.
'limit' is possibly 'undefined'.
The fix
Give limit the value it should have when nothing comes:
percent.tsts
function percentOf( added: number, limit = 5): number { return Math.round((added / limit) * 100);}console.log(`List ${percentOf(3)}% full`);
Read the last word of the message, as lesson 3.5 taught you:
'undefined' is what got through. ? let the call leave limit
out, and nothing in the body says what to divide by then. Run it
anyway, node percent.ts, and Node, which never checks, divides by
undefined and prints List NaN% full (NaN, not a number). With
the default it prints List 60% full.
So choose by what the body needs. When it does something different
with nothing, the way plan printed the task alone, use ? and
check. When it only needs the usual value, give a default: one
place, and no check anywhere in the body.
TypeScript refuses this program with 'minutes' is possibly 'undefined'. Add a check so that a call with no minutes gives back
the task alone. The program then prints pay rent: 1.5 h and
call mom.
Loading the editor…
Exercise · Fix the error
Give the limit a default
TypeScript refuses this program with Expected 2 arguments, but got 1. Change only the first line, so that a call with no limit uses 5.
The program then prints 7 and 2.
Loading the editor…
Exercise · Fix the error
Put the rest parameter last
This program should print Monday: 2 tasks. TypeScript refuses it
with A rest parameter must be last in a parameter list. A second
message, Expected 2 arguments, but got 3., comes from the same
line and goes away with it. Fix the first line; the call is already
right.
Loading the editor…
Exercise · Write the code
Write summary
Write a function summary that takes any number of minutes, one
for each task, and gives back a string saying how many tasks
there are and how many minutes they take together. summary(25, 15, 30) gives back "3 tasks, 70 min", and summary() gives back
"0 tasks, 0 min". The lines that call it are already there.
Loading the editor…
Recap
Recap · 3 questions
Check yourself
With minutes?: number, what type is minutes in the body?
Check yourself
Why does minutes = 15 need no type written?
Check yourself
With ...minutes: number[], what does total() put in minutes?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Optional, default, and rest parameters
What things are
Word
What it means
Optional parameter
One a call may leave out, marked with ?
Default value
What a parameter holds when it is left out
Rest parameter
The last one, holding every argument left as a list
... before a name
Makes the parameter a rest parameter
Code
Write
To
minutes?: number
Let a call leave it out; number | undefined
minutes = 15
Use 15 when it is left out; a number inside
...minutes: number[]
Take any number of numbers, as one list
plan("call mom")
Leave the minutes out
total(25, 15, 30)
Pass three; total() passes none
Rules
Rule
What it means
? needs a check
Before arithmetic, or TS18048: undefined got in
Default for undefined
Left out or undefined; 0 stays 0
Default, no type
The type comes from the value, as for a box
Rest is a list
[] when the call brings none
Order
Required, then optional or default, rest last
Wrong order
TS1016 for ?, TS1014 for a rest parameter
Too many arguments
TS2554 gives the range: Expected 1-2
Where to go next
Your functions are now as easy to call as the ones that came with
the language. You can mark a parameter with ? so a call may leave
it out, and check it before you use it. You can give a parameter a
default, so the body always has a value. And you can take any
number of arguments with a rest parameter, as one list. You know the
order they go in, and the message when it is wrong.
Next is Functions as values: callbacks and function types.
Every arrow you handed to map or reduce was a function passed
to another function as an argument. There you pass your own
functions around the same way, and write the type of a function.
Before you move on, make a file plan.ts in ~/projects/taskkit
with the plan from the first section, the one with
minutes?: number. Hover over minutes on its first line: VS Code
shows (parameter) minutes: number | undefined. Change ?: number
to = 15, delete the if block, and hover again. Then run
node plan.ts and check that call mom now comes with 15 minutes: