Functions can be typed by annotating parameters and return type. TypeScript infers return types when possible. Use function type expressions for callbacks, optional/default parameters for flexibility, and overloads for multiple signatures.
Basic Function Typing:
(param: type)function(): returnTypeFunction Type Expressions:
(params) => returnTypeSpecial Cases:
param?: typeparam: type = default...args: type[]// Parameter and return type annotations
function add(a: number, b: number): number {
return a + b;
}
// Return type inference (can omit if obvious)
function multiply(a: number, b: number) {
return a * b; // TypeScript infers number
}
// Arrow function typing
const subtract = (a: number, b: number): number => a - b;
// Function with object parameter
function greet(person: { name: string; age: number }): string {
return `Hello ${person.name}, you are ${person.age}`;
}
// Using interface for parameters
interface User {
name: string;
email: string;
}
function sendEmail(user: User, message: string): void {
console.log(`Sending to ${user.email}: ${message}`);
}