TypeScript Course
TypeScript
/
Advanced

Function Overloading

Definition

Providing multiple function type signatures for the exact same function name, allowing it to accept different combinations of arguments and return different types based on those arguments.

Explain Like I'm New

Overloading is a multi-tool pocket knife. To the user, it is one single tool called 'Cut'. But if they pass it a piece of paper, it acts like scissors. If they pass it a piece of wood, it acts like a saw. The function signature changes based on what you give it.

Real World Example

The DOM `document.createElement()` function. If you pass 'canvas', TS knows it returns an `HTMLCanvasElement`. If you pass 'div', it returns an `HTMLDivElement`.

Common Use Cases

  • •Complex utility functions
  • •Functions that can take either a single item or an array of items

Interactive Example

// 1. Overload Signatures (No function body, just types)
function makeDate(timestamp: number): Date;
function makeDate(m: number, d: number, y: number): Date;

// 2. Implementation Signature (Must be broad enough to handle all overloads)
function makeDate(mOrTimestamp: number, d?: number, y?: number): Date {
  if (d !== undefined && y !== undefined) {
    return new Date(y, mOrTimestamp - 1, d); // Months are 0-indexed
  } else {
    return new Date(mOrTimestamp);
  }
}

const d1 = makeDate(12345678); // Uses overload 1
const d2 = makeDate(5, 5, 2025); // Uses overload 2

// ERROR: No overload expects 2 arguments!
// const d3 = makeDate(5, 5);

Interview Questions

basic

  • How many implementation bodies does an overloaded function have?

intermediate

  • What is the 'Implementation Signature'?

advanced

  • Why is function overloading in TS fundamentally different from overloading in Java/C#?

Flash Cards

Question

How many implementation bodies?

Click to reveal answer
Answer

Exactly ONE. You write multiple signatures at the top, but you only write ONE actual function body that contains logic to check the types of the arguments and handle them.

Question

How does it differ from Java/C#?

Click to reveal answer
Answer

In Java, you literally write 3 completely separate functions with the same name. In TS, because JavaScript doesn't support multiple functions with the same name, you write 1 function body, and use TS solely to provide accurate intellisense hints to the developer.