Typescript Foundations / Functions

Function Overload

Function Overloading allows you to define multiple versions of a function with different parameter types or counts, while having a single implementation.

Useful when the function behaves differently based on the types or number of arguments.


✅ Basic Syntax

function func(x: string): string;
function func(x: number): number;
function func(x: any): any {
  return x;
}

🧠 Key Rules:

  • You write multiple function signatures (overloads).

  • Then write one actual implementation that handles all cases.


✍ Example 1: Combine Strings or Numbers

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

combine("Hello, ", "World!"); // "Hello, World!"
combine(10, 20);              // 30

✍ Example 2: Get User by ID or Name

function getUser(id: number): string;
function getUser(name: string): string;
function getUser(param: number | string): string {
  if (typeof param === "number") {
    return `User with ID ${param}`;
  } else {
    return `User with name ${param}`;
  }
}
getUser(101);     // "User with ID 101"
getUser("Codeveda"); // "User with name Codeveda"

✨ Why Use Overloading?

✅ Improves type safety

✅ Makes API easier to use

✅ Lets TypeScript understand different call patterns


⚠ Gotchas

  • The actual implementation must use union types or type guards (typeof, instanceof) to handle the variations.

  • Only the overload signatures are visible to the caller — not the implementation.


✅ Real-World Use Case: push() method


🔥 Summary

Term

Meaning

Overload signature

Declared interfaces a function can support

Implementation

A single function with logic for all cases

Type guard

Required to differentiate parameter types (typeof, Array.isArray, etc.)


✅ Function Overload Template:

function func(param1: TypeA): ReturnTypeA;
function func(param1: TypeB): ReturnTypeB;
function func(param1: TypeA | TypeB): ReturnTypeA | ReturnTypeB {
  // Implementation with type guards
}