04 functions
Functions are where most type information enters a TypeScript program Annotate the boundary, let inference handle the body
Table of Contents
Annotations
function greet(name: string): string {
return `Hello, ${name}`;
}
Parameter types are inputs Return type is the contract Write both on exported functions
Inside a function body, inference is usually enough Adding annotations everywhere is noise, not safety
Optional and rest
function build(label: string, value?: number, ...rest: string[]): string {
return [label, String(value ?? 0), ...rest].join(":");
}
? makes a parameter optional
... collects the rest into an array
Under strict mode an optional parameter is number | undefined, so ?? 0 is required
Arrow functions
const arrow = (n: number): number => n * 2;
Same types as a function declaration
Different this binding
Use arrows for callbacks and declarations, methods when you need dynamic this
Overloads
function format(value: string): string;
function format(value: number): string;
function format(value: string | number): string {
return String(value);
}
The overload signatures are what callers see The implementation signature is not visible to callers Use overloads when different inputs map to different output types
Return types
Letting TypeScript infer void or a concrete type is fine
Writing the return type on public functions documents intent and catches accidental changes
function fail(message: string): never {
throw new Error(message);
}
never means this function does not return
That is different from void, which means it returns nothing useful
Posted