CodeToLive

Functions in TypeScript

Functions in TypeScript are reusable blocks of code that perform a specific task. They can have typed parameters and return values, making your code more predictable and easier to debug.

Defining a Function

Functions in TypeScript are defined using the function keyword. Parameters and return types can be explicitly typed to ensure type safety.


function greet(name: string): void {
    console.log(`Hello, ${name}!`);
}

greet("Alice");  // Output: Hello, Alice!
      

Optional and Default Parameters

Parameters can be made optional by adding a ? or given default values. This allows for more flexible function calls.


function greet(name: string, age?: number): void {
    if (age) {
        console.log(`Hello, ${name}! You are ${age} years old.`);
    } else {
        console.log(`Hello, ${name}!`);
    }
}

greet("Alice");  // Output: Hello, Alice!
greet("Bob", 30);  // Output: Hello, Bob! You are 30 years old.
      

Arrow Functions

Arrow functions provide a concise syntax for writing functions. They are particularly useful for inline functions and callbacks.


const add = (a: number, b: number): number => a + b;
console.log(add(5, 10));  // Output: 15
      

Function Overloading

TypeScript supports function overloading, allowing you to define multiple function signatures for a single function. This is useful when a function can accept different types or numbers of parameters.


function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any {
    return a + b;
}

console.log(add(5, 10));  // Output: 15
console.log(add("Hello, ", "World!"));  // Output: Hello, World!
      

Rest Parameters

Rest parameters allow you to pass an arbitrary number of arguments to a function as an array. This is useful when the number of parameters is not fixed.


function sum(...numbers: number[]): number {
    return numbers.reduce((acc, curr) => acc + curr, 0);
}

console.log(sum(1, 2, 3, 4, 5));  // Output: 15
      

Function Types

In TypeScript, you can define types for functions. This is useful when you want to ensure that a variable or parameter is a function with a specific signature.


type AddFunction = (a: number, b: number) => number;

const add: AddFunction = (a, b) => a + b;
console.log(add(5, 10));  // Output: 15
      
Next: Classes and Objects