TypeScript allows you to type function parameters, return values, and even function signatures themselves. This makes it clear what a function expects and returns, reducing bugs significantly.
TypeScript
Beginner
10 min read
TypeScript Functions
Example
// Typed parameters and return type
function add(a: number, b: number): number {
return a + b;
}
// Optional and default parameters
function greet(name: string, greeting: string = 'Hello'): string {
return `${greeting}, ${name}!`;
}
// Rest parameters
function sum(...nums: number[]): number {
return nums.reduce((acc, n) => acc + n, 0);
}
// Function type
type MathOp = (a: number, b: number) => number;
const multiply: MathOp = (a, b) => a * b;
// Void return (no return value)
function logMessage(msg: string): void {
console.log(`[LOG] ${msg}`);
}
// Overloads
function format(value: string): string;
function format(value: number): string;
function format(value: string | number): string {
return typeof value === 'number' ? value.toFixed(2) : value.trim();
}
// Generic function
function first<T>(arr: T[]): T | null {
return arr.length > 0 ? arr[0] : null;
}
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