Syntax
function name(param: type): returnType { }Examples
Parameters and Return Types
The fundamentals of typing a function signature.
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
function logResult(value: number, label?: string): void {
// label is optional - type is "string | undefined"
console.log(label ? `${label}: ${value}` : value);
}
greet("Alice"); // uses default greeting
greet("Bob", "Hi"); // overrides itTyping a Function as a Value
Describing the shape of a function stored in a variable or passed as an argument.
let mathOperation: (a: number, b: number) => number;
mathOperation = (a, b) => a + b; // parameter types are inferred from the variable's type
function applyOperation(a: number, b: number, operation: (x: number, y: number) => number): number {
return operation(a, b);
}
console.log(applyOperation(5, 3, (x, y) => x * y)); // 15Best practices
- Always type function parameters explicitly - TypeScript cannot infer them the way it infers return types
- Place optional parameters after all required parameters in a function signature - required parameters cannot follow optional ones
- Let TypeScript infer the return type in most cases rather than annotating it explicitly, unless the function is part of a public API where an explicit contract is valuable
- Use a function type expression when a variable or parameter itself needs to hold a function, describing its expected signature precisely
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook