Functions
Typed function parameters, return annotations, optional parameters, defaults, and rest parameters.
TypeScript types parameters, return values, and functions as values. Start with the signature that callers need to understand.
Parameter types go after the name. Return types can be inferred, but an explicit annotation catches accidental changes.
function add(a: number, b: number): number {
return a + b;
}
const multiply = (a: number, b: number): number => a * b;
const greet = (name: string) => `Hello, ${name}!`;Optional parameters use ?. Default parameters use =. Rest parameters collect the remaining arguments into a typed array.
function createUser(
name: string,
role: string = "member",
email?: string,
): string {
const base = `${name} (${role})`;
return email ? `${base} <${email}>` : base;
}
function sum(...numbers: number[]): number {
return numbers.reduce((total, n) => total + n, 0);
}In production
Add explicit return types to exported functions and callback boundaries. They fail at the definition when behavior drifts, instead of leaking a widened type to every caller.
Enjoyed this? Get more software craft delivered to your inbox.