Typing Functions and Parameters
Annotate parameters, optional and default args, rest tuples, return types, and callback signatures — the function typing patterns every module uses.
Functions are where application logic lives and where type contracts matter most. TypeScript verifies callers pass correct arguments and implementations return promised shapes. Parameter types are never inferred from the body — always annotate them in .ts files. Return types can infer locally but should be explicit on exported APIs.
Optional parameters, defaults, and rest args mirror JavaScript runtime behavior while catching mistakes at compile time. Function type expressions describe callable shapes for callbacks, validators, and dependency injection independent of any single implementation.
Parameters, returns, and function types
Arrow functions and function declarations share the same typing rules. A type alias like (value: number) => string documents any compatible implementation — useful when passing formatters into utilities.
Hello, Ada!
87.5%Optional, default, and rest parameters
Optional (?) allows undefined explicitly. Defaults apply when the argument is missing or undefined. Rest collects remaining arguments into a typed array — essential for variadic math and logging helpers.
10void, never, and callbacks
void tells callers to ignore return values — typical for side effects. never marks functions that always throw. Callback types enable higher-order patterns: validators, event handlers, and middleware-style composition.
| Syntax | Meaning |
|---|---|
| name: T | Required |
| name?: T | Optional |
| name = expr | Default |
| ...rest: T[] | Rest array |
Overloads vs union parameters
Function overloads declare multiple call signatures for one implementation body — the signature list tells callers what combinations of arguments are legal and what return type each produces. TypeScript picks the matching overload at the call site. This shines when return type depends on input shape in a small finite set of cases, like document.getElementById returning HTMLElement | null depending on the id string.
When overload lists grow beyond two or three signatures, prefer a single signature with union parameters or generics instead. Overloads are powerful but harder to maintain — each new call pattern needs another overload line plus implementation logic that satisfies all branches. Union parameters with conditional return types cover many of the same cases with less ceremony.
- Always type parameters
- Annotate exported return types
- Use function types for callbacks
- Rest params as typed arrays
- 1Parameters need explicit types
- 2Optional vs default semantics differ
- 3void and never describe control flow
- 4Next: type narrowing and guards