Functions are the building blocks of any application. In TypeScript, you can add type annotations to function parameters and return values, making your code more predictable and catching errors early.
TypeScript allows you to specify types for both parameters and return values:
// Function with typed parameters and return type
function add(a: number, b: number): number {
return a + b;
}
// Function with no return value (void)
function greet(name: string): void {
console.log(`Hello, ${name}!`);
}
// Function that returns a boolean
function isEven(num: number): boolean {
return num % 2 === 0;
}
// Usage
const sum = add(5, 3); // 8
greet("TypeLand"); // "Hello, TypeLand!"
const result = isEven(4); // true
Arrow functions provide a concise syntax and work seamlessly with TypeScript's type system:
// Arrow function with explicit types
const multiply = (x: number, y: number): number => {
return x * y;
};
// Concise arrow function (implicit return)
const square = (n: number): number => n * n;
// Arrow function with no parameters
const getRandomNumber = (): number => {
return Math.random();
};
// Usage
console.log(multiply(4, 5)); // 20
console.log(square(6)); // 36
console.log(getRandomNumber()); // random number
TypeScript supports optional parameters (using ?) and
default values:
// Optional parameter (might be undefined)
function buildGreeting(name: string, title?: string): string {
if (title) {
return `Hello, ${title} ${name}!`;
}
return `Hello, ${name}!`;
}
console.log(buildGreeting("Alice")); // "Hello, Alice!"
console.log(buildGreeting("Bob", "Dr.")); // "Hello, Dr. Bob!"
// Default parameter value
function calculatePrice(price: number, taxRate: number = 0.1): number {
return price + (price * taxRate);
}
console.log(calculatePrice(100)); // 110 (default 10% tax)
console.log(calculatePrice(100, 0.2)); // 120 (20% tax)
// Multiple optional/default parameters
function createUser(
username: string,
email?: string,
age: number = 18
): object {
return { username, email, age };
}
You can also define function types as variables or use them in type aliases:
// Function type alias
type MathOperation = (a: number, b: number) => number;
// Use the function type
const subtract: MathOperation = (x, y) => x - y;
const divide: MathOperation = (x, y) => x / y;
console.log(subtract(10, 3)); // 7
console.log(divide(20, 4)); // 5
// Callback function type
function processNumbers(
nums: number[],
callback: (n: number) => number
): number[] {
return nums.map(callback);
}
const doubled = processNumbers([1, 2, 3], n => n * 2);
console.log(doubled); // [2, 4, 6]
Rest parameters allow functions to accept any number of arguments:
// Rest parameters collect remaining arguments into an array
function sum(...numbers: number[]): number {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20, 30, 40)); // 100
// Combine regular and rest parameters
function makeList(title: string, ...items: string[]): string {
return `${title}: ${items.join(', ')}`;
}
console.log(makeList("Fruits", "Apple", "Banana", "Orange"));
// "Fruits: Apple, Banana, Orange"
void for functions that don't return a value
? and must come after
required parameters