Skip to main content

Archive

Show more

Overload Function Signatures in TypeScript

Overload Function Signatures in TypeScript

Overloading function signatures in TypeScript allows you to define multiple function signatures for a single function, enabling the function to handle different types or numbers of parameters. This feature provides a way to create more flexible and type-safe functions.


Understanding Function Overloading

Function overloading involves specifying multiple function signatures for a single function implementation. Each signature defines a different set of parameter types or counts that the function can accept. The implementation must be capable of handling all the specified signatures.

Defining Overloaded Signatures

To overload a function, you first define multiple signatures, followed by a single implementation that can handle all the defined signatures.


function multiply(a: number, b: number): number;
function multiply(a: string, b: string): string;
function multiply(a: any, b: any): any {
  return a * b;
}

console.log(multiply(2, 3)); // Output: 6
console.log(multiply("Hello", 3)); // Output: HelloHelloHello

Examples of Overloading

Overloading with Different Parameter Types

Here’s an example of a function that can handle different types of parameters:


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

console.log(concatenate("Hello", "World")); // Output: HelloWorld
console.log(concatenate("The number is ", 42)); // Output: The number is 42
console.log(concatenate(5, 10)); // Output: 15

Overloading with Different Parameter Counts

In this example, a function is defined to handle different numbers of parameters:


function formatMessage(message: string): string;
function formatMessage(message: string, value: number): string;
function formatMessage(message: string, value?: number): string {
  if (value !== undefined) {
    return `${message} ${value}`;
  } else {
    return message;
  }
}

console.log(formatMessage("The value is")); // Output: The value is
console.log(formatMessage("The value is", 100)); // Output: The value is 100

Benefits of Function Overloading

  • Allows functions to handle various input scenarios in a type-safe manner
  • Improves code readability by grouping related functionality
  • Enhances maintainability by reducing the need for multiple function names

Conclusion

Function overloading in TypeScript provides a way to define multiple signatures for a function, making it more versatile and adaptable to different scenarios. By specifying various parameter types and counts, you can create functions that handle a range of inputs while maintaining type safety and improving code clarity. This feature helps in writing cleaner, more manageable code in TypeScript.

Comments