0
0
Typescriptprogramming~5 mins

Function overloads in Typescript

Choose your learning style9 modes available
Introduction

Function overloads let you create one function that works in different ways depending on the inputs. This helps make your code clearer and easier to use.

When a function needs to handle different types of inputs and return different types.
When you want to provide multiple ways to call the same function with different arguments.
When you want to keep your code organized by grouping similar functions into one.
When you want to improve code readability by showing all possible function signatures.
When you want TypeScript to check that function calls match one of the allowed patterns.
Syntax
Typescript
function functionName(param: Type1): ReturnType1;
function functionName(param: Type2): ReturnType2;
function functionName(param: Type1 | Type2): ReturnType1 | ReturnType2 {
  // function implementation
}

Each overload signature is written without a function body.

The last function with the body handles all cases and must cover all overloads.

Examples
This function can greet by name or by age, depending on the input type.
Typescript
function greet(name: string): string;
function greet(age: number): string;
function greet(value: string | number): string {
  if (typeof value === 'string') {
    return `Hello, ${value}!`;
  } else {
    return `You are ${value} years old.`;
  }
}
This function doubles a number or repeats a string.
Typescript
function double(value: number): number;
function double(value: string): string;
function double(value: number | string): number | string {
  if (typeof value === 'number') {
    return value * 2;
  } else {
    return value + value;
  }
}
Sample Program

This program shows a function that formats strings and numbers differently using overloads.

Typescript
function format(input: string): string;
function format(input: number): string;
function format(input: string | number): string {
  if (typeof input === 'string') {
    return `String: '${input}'`;
  } else {
    return `Number: ${input.toFixed(2)}`;
  }
}

console.log(format('hello'));
console.log(format(3.14159));
OutputSuccess
Important Notes

Overloads improve code clarity but all logic must be inside the single implementation.

TypeScript uses the overload signatures to check calls, not the implementation signature.

Always make sure the implementation covers all overload cases to avoid runtime errors.

Summary

Function overloads let one function handle different input types clearly.

Write multiple signatures without bodies, then one implementation with all logic.

Use overloads to improve code readability and type safety.