Typed Functions
Typed Functions in TypeScript
TypeScript lets you annotate every part of a function signature, catching mistakes before you run your code.
Return type annotations Place the return type after the parameter list:
function add(a: number, b: number): number { return a + b; }Optional and default parameters
- Optional (
param?: type) – the argument may be omitted; its value isundefinedinside the function. - Default (
param = value) – TypeScript infers the type from the default value.
Rest parameters Collect remaining arguments into a typed array:
function sum(...nums: number[]): number { return nums.reduce((a, b) => a + b, 0); }Function overloads Declare multiple signatures for the same function name, then provide a single implementation that satisfies them all. The overload signatures are compile-time only; callers see them as distinct.
Key points:
- The implementation signature must be compatible with every overload signature.
- TypeScript uses the overload signatures, not the implementation signature, for type-checking callers.
- Prefer overloads over
anywhen a function accepts meaningfully different argument shapes.
Code Examples
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
function repeat(text: string, times?: number): string {
return text.repeat(times ?? 1);
}
console.log(greet("Alice"));
console.log(greet("Bob", "Hi"));
console.log(repeat("Go! ", 3));Default parameters make arguments optional while providing a sensible fallback. The ?? operator handles the undefined case for optional params.
function sum(...nums: number[]): number {
return nums.reduce((acc, n) => acc + n, 0);
}
function logAll(prefix: string, ...items: string[]): void {
items.forEach(item => console.log(`[${prefix}] ${item}`));
}
console.log(sum(1, 2, 3, 4, 5));
logAll("INFO", "Server started", "Listening on port 3000");Rest parameters must be the last parameter and collect all remaining arguments into a typed array.
function format(value: string): string;
function format(value: number, decimals: number): string;
function format(value: string | number, decimals?: number): string {
if (typeof value === "string") return value.toUpperCase();
return value.toFixed(decimals ?? 2);
}
console.log(format("hello"));
console.log(format(3.14159, 3));Overloads let you describe multiple ways to call a function while keeping a single implementation.
Quick Quiz
1. What is the type of a rest parameter `...args`?
2. Which signature does TypeScript use to type-check callers of an overloaded function?
Was this lesson helpful?