Function Types and Overloads
Functions are the core building blocks of any application. TypeScript allows you to type function parameters, return values, and even define multiple signatures for a single function.
1. Typing Parameters and Return Values
You can declare types for each parameter, and type the return value after the parentheses:
function addNumbers(a: number, b: number): number {
return a + b;
}If a function does not return a value, use void:
function logMessage(message: string): void {
console.log(message);
}2. Optional and Default Parameters
Optional Parameters
You can make a parameter optional by appending a question mark (?) to its name. Optional parameters must appear after required parameters.
function greetUser(name: string, greeting?: string): string {
if (greeting) {
return `${greeting}, ${name}!`;
}
return `Hello, ${name}!`;
}Default Parameters
If a parameter has a default value, TypeScript infers its type automatically. You do not need a question mark for default parameters.
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}3. Rest Parameters
Rest parameters allow you to pass an arbitrary number of arguments to a function. Type them as arrays:
function calculateSum(message: string, ...numbers: number[]): string {
const sum = numbers.reduce((acc, num) => acc + num, 0);
return `${message} ${sum}`;
}4. Function Overloads
Sometimes, a function can accept different sets of arguments and return different types. TypeScript supports this through Function Overloads.
To write an overload:
- Declare one or more Overload Signatures (functions without a body).
- Write a single Implementation Signature (with a body) that is compatible with all overloads.
// Overload Signatures
function getLength(input: string): number;
function getLength(input: any[]): number;
// Implementation Signature
function getLength(input: any): number {
return input.length;
}
getLength("TypeScript"); // Valid
getLength([1, 2, 3]); // Valid
// getLength(123); // Error: No overload matches this call.5. Summary
- Type parameter lists and return values explicitly to prevent logical bugs.
- Append a question mark (
?) to mark parameters as optional. - Use rest parameter arrays to handle varying numbers of arguments.
- Define function overloads to handle multiple input combinations under a single implementation.