Skip to main content

Command Palette

Search for a command to run...

Understanding Function Overload in TypeScript

Handle function return types dynamically

Updated
2 min read
Understanding  Function Overload in TypeScript
R

I'm a professional frontend developer, currently learning to be fullstack.

What are Function Overloads?

Function Overloads in Typescript allow us to define multiple function signatures for the same function. Each signature specifies a particular set of parameter types and the corresponding return type. This feature enables TypeScript to perform accurate type checking and inference, ensuring the function behaves correctly with different argument combinations.

TLDR, Show me the code: TS Playground for example

How to Use Function Overloads

We define multiple function signatures to use function overloads above the actual function implementation. Each signature is specific to a set of arguments and the expected return type. The function implementation follows these signatures and handles different cases accordingly.

// Function signature for adding numbers and returning a number
function add(a: number, b: number): number;

// Function signature for concatenating strings and returning a string
function add(a: string, b: string): string;

// Function implementation that handles both cases
function add(a: any, b: any): any {
  return a + b;
}

Let's consider one more example.

function convertToUnit(value: number, convertToString?: boolean) {
  if (convertToString) return value.toString();
  return value;
}

In the above function, convertToUnit returns a union type of string | number, which loses the intellisense and other TS benefits. To overcome this, we can add the function signature for the functions based on convertToString the parameter value.

// Will return string if convertToString is true
function convertToUnit(value: number, convertToString: true): string;

// will return number if convertToString is false
function convertToUnit(value: number): number;

function convertToUnit(value: number, covertToString?: boolean) {
  if (covertToString) return value.toString();
  return value;
}

The convertedStringValue would have all the intellisense for strings and convertedNumValue all the intellisense for numbers.

TS Playground