Functions
Typing a function means annotating both its parameters and, usually, its return value — so a mistake in what a function is called with, or what it hands back, gets caught the same way any other type mismatch does.
Parameter and return types
function add(a: number, b: number): number { return a + b; } console.log(add(3, 4)); console.log(add("3", 4));
add.ts:6:14 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
The : number after the closing parenthesis is the return type — if the function body ever returned something other than a number, that line itself would fail to compile too.
Optional and default parameters
function greet(name: string, greeting: string = "Hello"): string { return `${greeting}, ${name}!`; } function tag(text: string, category?: string): string { return category ? `[${category}] ${text}` : text; } console.log(greet("Sam")); console.log(greet("Sam", "Hey")); console.log(tag("Server down")); console.log(tag("Server down", "urgent"));
Hello, Sam! Hey, Sam! Server down [urgent] Server down
greeting: string = "Hello" supplies a fallback used whenever the caller leaves that argument out. category?: string instead makes the parameter genuinely optional, with no default — inside the function it's either a string or undefined.
Function types
function transform(value: number, fn: (n: number) => number): number { return fn(value); } const doubled = transform(5, n => n * 2); console.log(doubled);
10
fn: (n: number) => number describes a function type directly — a callback that takes a number and returns a number — the same style of annotation you'd use for a variable.
category?) always has to come after every required parameter in the list — TypeScript won't let you put a required parameter after an optional one, since there'd be no way for a caller to skip the optional one without also skipping the required one after it. Default parameters follow the same rule.