Open In App

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.

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

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.




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.

Implementation Signature

A TypeScript Implementation Signature is the concrete function definition following Overload Signatures, specifying the actual logic and behavior of the function. It executes when the function is called based on the provided arguments. The implementation signature is not visible to external code; it’s an internal detail of the function.

Syntax

function functionName(parameter1: type1, parameter2?: type2): returnType {
    // Function body
}

Parameters

Example: In this example, the Implementation Signature in the greet function accommodates two Overload Signatures anticipating ‘string’ or ‘number’ arguments. It uses an ‘input’ parameter of type ‘any,’ allowing flexibility for various input types.




function greet(name: string): string;
function greet(age: number): string;
  
function greet(input: any): string {
  return `Hello, ${input}`;
}
  
console.log(greet('Geeks'));
console.log(greet(18));

Output:

Hello, Geeks
Hello, 18

Reference: https://www.typescriptlang.org/docs/handbook/2/functions.html#overload-signatures-and-the-implementation-signature


Article Tags :