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

Loading Code Playground...

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.