TypeScript Functions
Functions are where types pay off most. When parameters and return values are typed, every caller is checked automatically: pass the wrong thing, forget an argument or misuse the result and the compiler tells you before the code ever runs.
Parameter and return types
Annotate each parameter with : type, and the return type after the parameter list:
function area(width: number, height: number): number {
return width * height;
}
const greet = (person: string): string => `Hello, ${person}!`;
console.log(area(3, 4));
console.log(greet("Linh"));12
Hello, Linh!
The return type is optional — TypeScript infers it from the return statements. Writing it anyway is good practice for exported functions: if you accidentally return the wrong thing, the error appears inside the function instead of at some distant caller.
Functions that return nothing use void.
Wrong arguments are caught
function area(width: number, height: number): number {
return width * height;
}
console.log(area(3));
console.log(area(3, "4"));main.ts(5,13): error TS2554: Expected 2 arguments, but got 1.
main.ts(6,21): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
Plain JavaScript would happily print NaN for the first call and "34"-style surprises for others. TypeScript stops both.
Optional, default and rest parameters
| Syntax | Meaning |
|---|---|
x?: T |
optional; inside the function x is T | undefined |
x: T = value |
default value used when the argument is missing; type can be inferred |
...xs: T[] |
rest parameter: any number of extra arguments collected into an array |
Optional and default parameters must come after the required ones.
function label(text: string, suffix?: string): string {
return suffix ? `${text} (${suffix})` : text;
}
function repeat(text: string, times = 2): string {
return text.repeat(times);
}
function sum(...values: number[]): number {
return values.reduce((total, v) => total + v, 0);
}
console.log(label("Report"), "|", label("Report", "draft"));
console.log(repeat("ab"), repeat("ab", 3));
console.log(sum(), sum(1, 2, 3, 4));Report | Report (draft)
abab ababab
0 10
Function types
Functions are values, so they have types too. A function type looks like an arrow function signature: (a: number, b: number) => number. Give it a name with a type alias and use it for callbacks:
type BinaryOp = (a: number, b: number) => number;
const add: BinaryOp = (a, b) => a + b; // a and b inferred as number
const times: BinaryOp = (a, b) => a * b;
function applyAll(ops: BinaryOp[], x: number, y: number): number[] {
return ops.map((op) => op(x, y));
}
console.log(applyAll([add, times], 6, 7));[ 13, 42 ]
Notice that add didn't annotate a and b. Because the variable already has a function type, TypeScript gives the parameters their types from context — this is called contextual typing, and it is why callbacks passed to map, filter and friends rarely need annotations.
void and never
void— the function returns no useful value.never— the function never returns at all: it always throws or loops forever.
function logLine(message: string): void {
console.log(`> ${message}`);
}
function fail(message: string): never {
throw new Error(message);
}
logLine("starting");
try {
fail("disk full");
} catch (err) {
console.log("caught:", (err as Error).message);
}> starting
caught: disk full
Tip: The
thisvalue inside a function can be typed too, with a fake first parameter:function onClick(this: Button) { … }. It is erased in the emitted JavaScript.
Test yourself
How do you mark a parameter as optional?
name: string?name?: stringoptional name: stringname: string | optional
Which return type fits a function that always throws an error?
- void
- undefined
- never
- null
Why can const add: BinaryOp = (a, b) => a + b omit the parameter types?
- Parameters default to
any - Contextual typing takes them from
BinaryOp - Arrow functions are never type-checked
- Because
+works on any type