Learn the concept
Function Types
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}`);
}Typing Express/Hono middleware chains with proper request/response generics
Creating type-safe event systems where handler signatures match event payload types
Typing React HOCs and render props with proper generic forwarding
Build an EventEmitter where emit() enforces correct payload types per event name
Implement a pipe() utility that chains functions with type-safe input/output inference