TypeScript Basics: JavaScript with Types
Typing Functions
In this lesson you will
- Add parameter and return types to a function
- Use optional and default parameters
- Write a type for a function that is passed around
Introduction
Functions are where types pay off most. A function is a promise: "give me these inputs and I will give you this output". Types write that promise down, so every caller and the function itself can be checked against it.
Parameter and return types
width: numbertypes each parameter. You almost always annotate parameters, because TypeScript cannot guess them.: numberafter the brackets is the return type. It is often optional, since TypeScript infers it from thereturn, but writing it documents your intent and catches mistakes inside the function.
Return the wrong thing and TypeScript tells you:
Calling a function with the wrong number of arguments is an error too:
Quick quiz
In function f(a: number): string, what is string?
Optional and default parameters
Add ? to make a parameter optional. Inside the function its type includes undefined, so check before using it.
A default value also makes a parameter optional and gives it a type automatically:
void: no return value
A function that returns nothing has the return type void.
Rest parameters
Rest parameters collect extra arguments into an array. Type it as an array:
Function types
Sometimes a function is a value you pass to another function, like a callback. Describe its shape with an arrow-style type:
(n: number) => number reads as "a function that takes a number and returns a number". Notice you didn't have to annotate n in the arrow functions: TypeScript knows the callback's parameter type from fn's type. This is called contextual typing.
Quick quiz
What does (text: string) => number describe?
Try it yourself
Write a function average that takes an array of numbers and returns their average as a number. Give it parameter and return types. For an empty array, return 0. The stub below has a deliberate mistake in the parameter type: the type checker complains when you call it with numbers.
Summary
- Annotate parameters, and consider annotating the return type.
?and default values make parameters optional.voidmeans nothing is returned.- Rest parameters are typed as arrays, like
...numbers: number[]. - Describe callbacks with a function type such as
(n: number) => number.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading