TypeScript
Beginner
1 min read
Function Types, Overloads, and Optional Parameters
Example
// Basic function type annotation
function add(a: number, b: number): number {
return a + b;
}
// Function type alias
type BinaryOp = (a: number, b: number) => number;
const multiply: BinaryOp = (a, b) => a * b;
// Optional and default parameters
function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
console.log(greet("Alice")); // Hello, Alice!
console.log(greet("Bob", "Hi")); // Hi, Bob!
// Rest parameters
function sum(...numbers: number[]): number {
return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
// Function overloads
function format(value: string): string;
function format(value: number, decimals: number): string;
function format(value: string | number, decimals?: number): string {
if (typeof value === "string") return value.trim();
return value.toFixed(decimals ?? 2);
}
console.log(format(" hello ")); // "hello"
console.log(format(3.14159, 2)); // "3.14"
// void vs never return types
function logInfo(msg: string): void {
console.log("[INFO]", msg);
}
function panic(msg: string): never {
throw new Error(msg);
}
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript