Open In App

TypeScript Function Overloads

Typescript Function overloads allow you to define multiple function signatures for a single function, each with different parameter types or return types. Function overloads help provide more accurate type checking and enable TypeScript to infer and enforce the correct types when you call the function in different ways.

Syntax:

// Function signature for the first overload
function functionName(parameter1: type1, parameter2: type2): returnType1;
// Function signature for the second overload
function functionName(parameter1: type3, parameter2: type4): returnType2;
// Implementation of the function that matches one of the overloads
function functionName(parameter1: any, parameter2: any): any {
// Function implementation here
}

Parameters:

Example 1: In this example, We define two overloads for the greet function. The first overload accepts only the name of the typed string, and the second overload accepts both name (a string) and age (a number). The implementation of the greet function checks whether age is defined to determine the appropriate greeting message.






function greet(name: string): string;
function greet(name: string, age: number): string;
 
function greet(name: string, age?: number): string {
    if (age === undefined) {
        return `Hello, ${name}!`;
    } else {
        return `Hello, ${name}! You are ${age} years old.`;
    }
}
 
console.log(greet("Geeks"));
console.log(greet("xyz", 30));

Output:

Hello, Geeks!
Hello, xyz! You are 30 years old.

Example 2: In this example, We define two overloads for the processInput function. The first and second overload accepts a string, returns a string and accepts a number and returns a number respectively. Inside the implementation, we use typeof checks to determine the type of the input and provide different behavior based on the type.






function processInput(input: string): string;
function processInput(input: number): number;
function processInput(input: string | number): string | number {
    if (typeof input === "string") {
        return `You entered a string: ${input}`;
    } else if (typeof input === "number") {
        return input * 2;
    }
}
 
console.log(processInput("Hello, GeeksforGeeks!"));
console.log(processInput(44));

Output:

You entered a string: Hello, GeeksforGeeks!
88

Article Tags :