Introduction
Functions are where most mistakes happen in JavaScript: an argument missing, given in the wrong order, or of the wrong kind. TypeScript checks every call against the function's signature, the list of parameter types and the return type. This lesson shows how to write them, how to make parameters optional, and how to type functions that are passed around as values.
How it works
Each parameter gets a type, and the return type comes after the parentheses:
function area(width: number, height: number): number {
return width * height;
}
area(3); // error TS2554: Expected 2 arguments, but got 1.
area(3, "4"); // error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
The return type can be inferred, but writing it is a good habit: it is a promise, and the checker then tells you if some path forgets to return a value.
Three kinds of parameter make calls flexible:
- An optional parameter,
title?: string, may be left out. Inside the function its type isstring | undefined, so you must check it before use. - A default parameter,
height: number = width, takes the default when left out, so inside it is always a number. - A rest parameter,
...prices: number[], collects any number of arguments into an array.
Functions are values in JavaScript, and a function type describes one: (a: number, b: number) => number is any function taking two numbers and returning a number. A type alias gives it a name, type Operation = ..., and then a callback parameter of that type is checked just like a variable. When you write an arrow function where an Operation is expected, you do not need to annotate its parameters: TypeScript knows them from the context.
Two return types say something special. void means the function returns nothing useful, as with a function that only prints. never means the function never returns normally, for example one that always throws an error.
Example
// Parameter types, return types, optional and default parameters, and function types.
function area(width: number, height: number = width): number {
return width * height;
}
function greet(name: string, title?: string): string {
return title ? "Hello, " + title + " " + name : "Hello, " + name;
}
function total(...prices: number[]): number {
return prices.reduce((sum, p) => sum + p, 0);
}
type Operation = (a: number, b: number) => number;
const add: Operation = (a, b) => a + b;
const times: Operation = (a, b) => a * b;
function apply(op: Operation, x: number, y: number): number {
return op(x, y);
}
console.log(area(3, 4), area(5));
console.log(greet("Ada"), "/", greet("Turing", "Dr"));
console.log(total(5, 10, 20));
console.log(apply(add, 2, 3), apply(times, 2, 3));Line by line
areahas a default forheight, soarea(5)means a 5 by 5 square.greethas an optionaltitle; the function checks it before using it.totalcollects all its arguments into the arrayprices.Operationnames a function type;addandtimesfit it, and their parameters need no annotation.applytakes anOperationas a parameter and calls it.
Expected result
12 25
Hello, Ada / Hello, Dr Turing
35
5 6
In the real world
Library authors rely on typed signatures as documentation that cannot go out of date: hovering over a function in an editor shows its parameter and return types. Event handlers, array methods such as map and filter, and promise callbacks are all typed with function types, which is why the editor knows what the parameter of your arrow function holds.
Common mistakes
- Using an optional parameter without checking it: it may be undefined.
- Putting an optional parameter before a required one: optional parameters must come last.
- Typing a callback as Function: that accepts any function and checks nothing; write the full function type.
- Forgetting a return on one path when the return type is not void.
Best practices
- Write parameter and return types on every exported or shared function.
- Prefer a default value to an optional parameter when there is a sensible default.
- Name function types that appear more than once with a type alias.
Summary
A function's signature lists its parameter types and its return type, and TypeScript checks every call against it: how many arguments and of what type. Parameters can be optional (?), have defaults (=) or collect the rest (...). Function types such as (a: number) => string let callbacks be checked too, and void and never describe functions that return nothing or never return.
Quick check
Key takeaways
- TypeScript checks every call: the number of arguments and each argument's type.
- Mark parameters optional with ?, give defaults with =, collect extras with ...rest.
- Function types describe callbacks so that they are checked too.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.