Typing Functions
10 min read
Typing Functions
TypeScript lets you annotate function parameter types and the return type. Annotating the return type is especially valuable — it prevents accidentally returning the wrong thing.
ts
// Named function
function add(a: number, b: number): number {
return a + b;
}
// Arrow function
const multiply = (a: number, b: number): number => a * b;
// Function type alias
type MathOp = (a: number, b: number) => number;
const divide: MathOp = (a, b) => a / b;Optional and default parameters
ts
function greet(name: string, greeting?: string): string {
return `${greeting ?? "Hello"}, ${name}!`;
}
// Default parameter (implies optional)
function createUser(name: string, role: string = "student") {
return { name, role };
}
greet("Alice"); // "Hello, Alice!"
greet("Alice", "Hi"); // "Hi, Alice!"Rest parameters and void
ts
function logAll(...messages: string[]): void {
messages.forEach((m) => console.log(m));
}
// void vs undefined
// void: the return value won't be used
// undefined: the function explicitly returns undefined
function noop(): void {}
function returnsUndefined(): undefined { return undefined; }TypeScript infers return types automatically, but explicitly annotating them is good practice for exported functions. It catches mistakes like forgetting a return in a branch.
Ready to test yourself?
Practice TypeScript— quiz & coding exercises