Overload Signatures

TypeScript Overload Signatures allow defining multiple function declarations with the same name but different parameter types or counts. They enable precise type checking and provide documentation for various function usage.

Syntax

function functionName(parameter1: type1): returnType1;
function functionName(parameter1: type1, parameter2: type2): returnType2;

Parameters

  • functionName: This is the name of the function you’re defining.
  • parameter1, parameter2, …: These are the parameters that the function can accept in different overload signatures.
  • type1, type2, …: These are the types of the corresponding parameters in the overload signatures.
  • returnType1, returnType2, …: These are the return types of the function in different overload signatures.

Example: In this example, the calculateSquare function uses TypeScript Overload Signatures to either square a number or inform that a string can’t be squared. Outputs: 4 (square of 2) and Geeks cannot be squared.

Javascript




function calculateSquare(x: number): number;
function calculateSquare(x: string): string;
function calculateSquare(x: any): any {
    if (typeof x === 'number') {
        return x * x;
    } else if (typeof x === 'string') {
        return `${x} cannot be squared.`;
    }
}
  
console.log(calculateSquare(2));
console.log(calculateSquare('Geeks'));


Output:

4
Geeks cannot be squared.

TypeScript Overload Signatures and Implementation Signature

TypeScript Overload Signatures define multiple function declarations with the same name but different parameter types or counts. Implementation Signatures provide the actual function definition matching one of the declared overloads. The common confusion between overload signatures and implementation signatures in TypeScript often arises because the signature used to write the function body (the implementation signature) cannot be seen from the outside of the function.

Similar Reads

Overload Signatures

TypeScript Overload Signatures allow defining multiple function declarations with the same name but different parameter types or counts. They enable precise type checking and provide documentation for various function usage....

Implementation Signature

...