Write a few lines once and run them whenever you like: declare a function with a name, typed parameters and a return type, call it with arguments, and use the value that return hands back. Follow a call into the body and out again, see why a parameter’s type must always be written, and how TypeScript checks every call, the body and the return against the first line. TaskKit gets its first function, capitalize.
Fundamentals
TypeScript
Declaring functions: parameter and return types. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
In a kitchen drawer there is a card in your grandmother's
handwriting. At the top it says Pancakes, under that For: 4
people and Makes: 12, and then the steps. Nobody writes the
recipe out again every Sunday. You take the card, say how many
people are coming, follow the steps, and get pancakes. The card was
written once, and it is used every week with whatever you bring.
Your code has no named cards yet. In lesson 2.4 TaskKit gave two
tasks a capital first letter, and you wrote the same long line
twice, once for tidyFirst and once for tidySecond. Since lesson
2.8 there is only one copy, because every task you type goes
through the same lines. The next place in the file that needs a
capital letter means another copy, and the day you find a slip in
it, you fix one copy and forget the other. In this lesson you write the
card instead: a few lines with a name, written once and run
whenever you like. By the end you will write your own, say with
types what goes in and what comes out, and TaskKit's long line will
be one short call.
A name for a few lines
You have been running code that somebody else wrote since your
first lesson. console.log("Hi") runs lines that live inside Node,
and hands them the text in the parentheses. task.trim() does the
same with lines that belong to every string. Lesson 4.3 gave the
idea its name: a function is a piece of code with a name, which
you can run later, as often as you like. Now you write your own,
and give it a name, which lesson 4.3's rules never had.
ts
function left(used: number): number { return 60 - used;}
This one works out how many minutes of an hour are left once some
are used. It is a function declaration: the word function,
the function's name, what it takes in parentheses, and its
body in braces, the lines it runs. Read it the way you read the
recipe card, part by part:
In the codeOn the recipe cardName
left
What you call it by
Pancakes
What you look it up by
Parameter
used:number
What goes in, and its type
For:…people
A gap for what you bring each time
Return type
:number
What comes out, and its type
Makes:…pancakes
What you get back, and what kind
Body
{return…}
The work, run at every call
Thesteps
Followed every Sunday
Every part of the function has its place on the recipe card
The table leaves gaps where the card says 4 and 12. Those are the
numbers your grandmother wrote down, not the only ones you can bring.
A parameter and a return type say what kind of value goes in and
comes out, not which one.
Declaring a function runs nothing, the way a card in a drawer cooks
nothing. Its body runs only when something calls it: the
function's name, then parentheses holding what you bring. Run this:
It prints 35 and then 10. Each call runs the body again from
the top, with a new value. Two calls, two answers, and one body to
read and to fix.
What happens at a call
A call is a short trip. The computer stops in the middle of the
line that calls, goes into the function, runs its body, and comes
back with a value. Three words name the parts of the trip:
A parameter is the box a function makes for what you bring:
used. Lesson 4.3 met the word on the left of an arrow; here it
sits in the parentheses after the function's name.
An argument is the value you put in it at a call: 25.
Lesson 1.6 met both words in an error message.
return hands a value back to the line that called, the
caller, and ends the call. The value is the call's return value.
Here is one program making two calls. Press Next step to follow
it one step at a time, or Play:
The box used existed only while its call ran, the way task in
lesson 4.2's for...of existed only inside its loop.
Now press Step on the same program and watch its Call stack
column, which every Step player in this course has had: on line
2 it says global › left, inside a call of left; back on line 4
it says global, the file itself. Lesson 5.8 is about that column.
The types at both ends
Lesson 2.6 promised a place where there is nothing to infer a type
from, and this is it. When TypeScript reads function left(used),
used has no value yet. Its value arrives later, from a call that
could be anywhere in the file. So you write the parameter's type
yourself, after a colon, the way you write one on a box:
used: number.
Bad — no type on the parameter, so
TypeScript would have to accept anything as task.
Good — task: string, so every
call and every line of the body is checked against it.
The first is refused with TS7006 (TS for TypeScript, then the
number of this kind of error): Parameter 'task' implicitly has an 'any' type.any is TypeScript's word for "anything at all", and Module
8 has a lesson on it. A parameter that could be anything cannot be
checked, so TypeScript will not guess. The second prints
Buy milk.
The return type goes after the parentheses: ): string.
TypeScript could infer it from the return, the way it infers a
box's type from its value. Written down, it becomes a promise:
whatever the body does, it gives back a string, and TypeScript
holds the body to it. With both types written, the first line is
everything a caller needs, and TypeScript checks it from three
sides:
At the call: the argument against the parameter
Argument of type 'string' is not assignable to parameter of type
'number'.
In the body: the parameter is a number
Property 'length' does not exist on type 'number'.
At the return: the value against the return type
Type 'number' is not assignable to type 'string'.
One typed line, checked from three sides
The first example is the message lesson 1.6 taught you to read for
repeat("28"): the argument "25" is a string, and the parameter
wants a number. A call with the wrong number of arguments is refused
the same way, with TS2554: left() gets
Expected 1 arguments, but got 0., and left(25, 40) gets
Expected 1 arguments, but got 2.
Several parameters, filled in order
A function can take several parameters, separated by commas, each
with its own type. A call fills them in order: the first argument
goes in the first parameter, the second in the second. Here is
TaskKit's percentage from lesson 2.5 as a function:
The first line prints List 60% full. The second swaps the
arguments and prints List 167% full, and TypeScript says nothing,
because both are numbers. The types check what kind of value goes
in; only the names say which one goes first. That is why a
parameter gets a name as clear as a box's.
return gives back, and stops
return does two things at once: it hands the value back, and it
ends the call right there. Nothing after it in the body runs. That
lets a function answer early, as soon as it knows the answer:
It prints quick long. For 10, the if is true, the first return
hands back "quick", and the last line of the body never runs. For
40, the if is false, so the body goes on to the second return.
Both ways through the body end at a return that gives back a string,
which is what : string promised.
That promise holds for every way through the body. Delete the body's
last line, return "long";, and TypeScript refuses the function with
TS2366: Function lacks ending return statement and return type does not include 'undefined'. For 40 the body would end without a
return, and a call that ends that way gives back undefined, which
is not the string : string promised.
TaskKit gets its first functions
Now TaskKit's step for this lesson, the first piece of this
module's work: turning TaskKit into small functions. The long line
that gives a task its capital letter becomes a function, and add
calls it. The line that works out how full the list is becomes a
second one.
Open index.ts in ~/projects/taskkit. At the very top of the
file, above const version = "0.1";, declare the function:
Then, in the add case, replace the two lines that build newTask
with a call:
Then the percentage. Declare percentFull from this lesson right
under capitalize:
Its parameters have the same names as the file's boxes added and
limit. That is allowed: a parameter is the function's own box,
made fresh at each call, and lesson 5.5 shows why the names do not
clash.
Near the end of the file, make the line that works out percent
call it:
The comment moves with the rounding: it now sits inside
percentFull, above the line it explains.
Check the file with tsc (the TypeScript compiler, which npx
starts) and run it with the tasks from lesson 4.4:
npx tsc prints nothing: the file passes. Then TaskKit prints:
Exactly what it printed before. That is the point of the change:
TaskKit does the same work, and the rule for a capital letter and
the arithmetic for the percentage each live in one place, with a
name that says what it does.
Predict before you run
This function answers early when the list is full. Follow each call
into the body, and count every line printed, inside the function
and outside it.
Predict
How many lines does this program print?
The common mistake: no return
A body that works the answer out looks finished. It is easy to
write the line that does the work and forget the word that hands
the result back.
Common mistake
Working the value out and never returning it
You want TaskKit's percentage as a function, so you move its line
into a body:
npx tsc --noEmit--types node percent.ts refuses it before it
runs:
The first line is one long line in your terminal, broken in two
here to fit the page.
A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value.
The fix
Hand the value back with return:
Read the start of the message as a list of the types that are
allowed to give nothing back: void is lesson 5.6's subject, and
any you met above. The part that matters is the end, must return
a value, and the wavy line under number: the promise you wrote is
the one the body broke. Without : number, nothing would refuse
the file, Node would print List undefined% full, and the mistake
would reach your screen. So write the return type, and when this
error appears, look for the return the body is missing.
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.
Recap
Recap · 3 questions
Check yourself
What does return do?
Check yourself
Why do you write a parameter's type yourself?
Check yourself
You declare a function and never call it. What runs?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Declaring functions: parameter and return types
What things are
Word
What it means
Function
Code with a name, run whenever it is called
Declaration
function, a name, parameters, and a body
Body
The lines in braces, run at every call
Call
The name and parentheses, such as left(25)
Parameter
The box a function makes for what you bring
Argument
The value a call puts in that box
Return value
What a call gives back, in its place
Return type
The type the function promises to give back
Code
Write
To
function left(…) { … }
Declare a function called left
(used: number)
Take one parameter; its type always written
percentFull(3, 5)
Fill two parameters in order: 3, then 5
): number {
Promise what comes out
return 60 - used;
Hand a value back and end the call
const free = left(25);
Call it and keep what it gives back
Rules
Rule
What it means
Declared is not run
The body runs only when it is called
A fresh box each call
used exists only while its call runs
No parameter type
TS7006: TypeScript will not guess
Return type written
Where to go next
You can now write a function: a name, typed parameters, a return
type, and a body that hands its answer back with return. You can
call it with arguments, use the value it gives back, and read the
errors TypeScript gives when a call or a body breaks the first
line's promise. TaskKit has its first two functions.
Next is Arrow functions. The short rules you handed to map
and filter in lesson 4.3 are functions too. In the next lesson
you write them with braces, types and return, and learn when an
arrow is a better choice than function.
Before you move on, move TaskKit's room arithmetic into a function
roomLeft(added: number, limit: number): number, call it on the
line that makes room, and check with npx tsc and a run that the
output is unchanged.
No return is TS2355; one way without, TS2366
Wrong argument
TS2345; the wrong count is TS2554
After return
Nothing else in the body runs
Exercise · Read the code
Follow a return value into a call
What does this program print?
ts
function left(used: number): number { return 60 - used;}const first = left(20);const second = left(first);console.log(second);
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Added: Pay rentAdded: Call MomAdded: Buy milkAdded: Call dadTasks added: 4 of 5, room for 1 moreList 80% fullYour list, A to Z:1. Buy milk2. Call dad3. Call Mom4. Pay rent
Outputtext
percent.ts:1:53 - error TS2355: A function whose declared type isneither 'undefined', 'void', nor 'any' must return a value.1 function percentFull(added: number, limit: number): number { ~~~~~~Found 1 error in percent.ts:1
left.tsts
function left(used: number): number { return 60 - used;}console.log(left(25));console.log(left(50));
left.tsts
function left(used: number): number { return 60 - used;}const afterMilk = left(25);const afterWalk = left(40);console.log(afterMilk, afterWalk);
ts
function capitalize(task) { return task.slice(0, 1).toUpperCase() + task.slice(1);}console.log(capitalize("buy milk"));
function roomMessage(added: number): string { if (added >= 5) { return "The list is full"; } console.log("Counting the room"); return `Room for ${5 - added} more`;}console.log(roomMessage(5));console.log(roomMessage(3));
percent.tsts
function percentFull(added: number, limit: number): number { Math.round((added / limit) * 100);}console.log(`List ${percentFull(3, 5)}% full`);
percent.tsts
function percentFull(added: number, limit: number): number { return Math.round((added / limit) * 100);}console.log(`List ${percentFull(3, 5)}% full`);
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 left(used: number): number { return 60 - used;}const afterMilk = left(25);const afterWalk = left(40);console.log(afterMilk, afterWalk);
MemoryThe boxes in memory, each with its name. A box appears when a line makes it; the one just filled or changed is orange.
used2525
afterMilk3535
afterWalk2020
OutputEverything the program has printed so far.
Nothing printed yetNothing printed yet
Every step as text
Line 4.
Line 4 calls left with 25. The computer leaves the line half
done and goes into the function.
Line 2.used = 25.
Inside left, a fresh box used holds the argument, 25, and
return works out 60 − 25.
Line 4.afterMilk = 35.
return handed back 35. The call is replaced by it, and 35 goes
in the box afterMilk.
Line 2.afterMilk = 35, used = 40.
Line 5 calls again, with 40: a new used, the same body, and
60 − 40.
Line 5.afterMilk = 35, afterWalk = 20.
return handed back 20, and 20 goes in the box afterWalk.
Line 6.afterMilk = 35, afterWalk = 20.
Both boxes are printed on one line: 35 20.
Prints 35 20
A call goes into the function and comes back with a value
Exercise · Fix the error
Give the parameter its type
TypeScript refuses this program with Parameter 'task' implicitly has an 'any' type. Fix the first line so it runs and prints
BUY MILK. Write its return type too, as this lesson does.
Loading the editor…
Exercise · Fix the error
Hand the hours back
hours should turn minutes into hours, so this program should
print 1.5. TypeScript refuses it. Fix the body without changing
its first line.
Loading the editor…
Exercise · Write the code
Write taskLine
Write a function taskLine that takes a task as a string and its
minutes as a number, and gives back one string:
taskLine("buy milk", 25) gives back "buy milk: 25 min". The line
that calls it is already there.