Functions in TypeScript
Declare precise function types and use generics, overloads, and this parameters where needed.
Signatures and parameters
function greet(name: string, excited = false): string {
return excited ? `Hello, ${name}!` : `Hello, ${name}.`;
}
function sum(...nums: number[]): number {
return nums.reduce((a, b) => a + b, 0);
}
Optional parameters use ? and must be last.
Function types and arrows
type Comparator<T> = (a: T, b: T) => number;
const cmp: Comparator<number> = (a, b) => a - b;
Arrow functions capture this lexically.
Overloads
Provide multiple call signatures with a single implementation.
function pick(id: number): HTMLElement;
function pick(sel: string): NodeListOf<Element>;
function pick(x: number | string) {
return typeof x === "number"
? document.getElementById(String(x))!
: document.querySelectorAll(x);
}
Use the union type in the implementation; keep overloads minimal and clear.
this parameter
Annotate expected this for callbacks and methods.
interface Button { onClick(cb: (this: HTMLButtonElement, ev: MouseEvent) => void): void }
Generics and constraints
function first<T>(xs: T[]): T | undefined { return xs[0]; }
function pluck<T, K extends keyof T>(xs: T[], key: K): T[K][] {
return xs.map(x => x[key]);
}
Prefer generic constraints to express relationships between parameters.
Return types: void vs never
void: no meaningful returnnever: does not return (throws/loops)
Summary
- Model functions with precise parameter and return types
- Use overloads sparingly, generic constraints for relationships, and
thisparameters when needed