Functions, Overloads & Typing Patterns

0/6 in this phase0/21 across the roadmap

📖 Concept

TypeScript provides rich typing for functions — from basic parameter/return types to generics, overloads, and advanced patterns like this typing.

Function type expressions: (param: Type) => ReturnType Optional and default parameters: param?: Type or param: Type = defaultValue Rest parameters: ...args: Type[] Function overloads: Multiple signatures for different input/output combinations

Function Overloads let you define multiple call signatures for a single function. The compiler chooses the right signature based on the arguments. The implementation signature must be compatible with ALL overload signatures.

this typing: TypeScript can type the this parameter explicitly — useful for callbacks that need a specific context.

Callback typing patterns:

  • (data: T) => void — Standard callback
  • (err: Error | null, data?: T) => void — Node.js error-first callback
  • () => Promise<T> — Async factory

🏠 Real-world analogy: Function overloads are like a Swiss Army knife — the same tool (function name) provides different tools (behavior) depending on how you open it (what arguments you pass).

💻 Code Example

codeTap to expand ⛶
1// Basic function typing
2function add(a: number, b: number): number {
3 return a + b;
4}
5
6// Arrow function type
7const multiply: (a: number, b: number) => number = (a, b) => a * b;
8
9// Optional and default parameters
10function greet(name: string, greeting: string = "Hello"): string {
11 return `${greeting}, ${name}!`;
12}
13greet("Alice"); // "Hello, Alice!"
14greet("Alice", "Hola"); // "Hola, Alice!"
15
16// Rest parameters
17function sum(...numbers: number[]): number {
18 return numbers.reduce((acc, n) => acc + n, 0);
19}
20
21// ⭐ Function Overloads
22function createElement(tag: "a"): HTMLAnchorElement;
23function createElement(tag: "canvas"): HTMLCanvasElement;
24function createElement(tag: "input"): HTMLInputElement;
25function createElement(tag: string): HTMLElement;
26function createElement(tag: string): HTMLElement {
27 return document.createElement(tag);
28}
29const anchor = createElement("a"); // Type: HTMLAnchorElement
30const canvas = createElement("canvas"); // Type: HTMLCanvasElement
31
32// Practical overload: different return based on input
33function parseInput(input: string): string;
34function parseInput(input: number): number;
35function parseInput(input: string | number): string | number {
36 if (typeof input === "string") return input.trim();
37 return Math.round(input);
38}
39
40// Typing 'this'
41interface Button {
42 label: string;
43 onClick(this: Button): void;
44}
45const button: Button = {
46 label: "Submit",
47 onClick() {
48 console.log(this.label); // 'this' is typed as Button
49 }
50};
51
52// Generic function (preview — deep dive in Phase 2)
53function identity<T>(value: T): T {
54 return value;
55}
56const str = identity("hello"); // Type: string
57const num = identity(42); // Type: number
58
59// Function type with generics
60type Mapper<T, U> = (item: T, index: number) => U;
61const toLength: Mapper<string, number> = (s) => s.length;
62
63// Void vs undefined return
64type VoidFn = () => void;
65const fn: VoidFn = () => { return true; }; // ✅ No error! void ignores return
66// This is intentional — allows array.forEach() to accept callbacks that return values

🏋️ Practice Exercise

Mini Exercise:

  1. Write overloaded function signatures for a format function that accepts string → string or number → string
  2. Create a typed callback pattern: function fetchData(url: string, cb: (err: Error | null, data?: string) => void)
  3. Type a method with explicit this parameter for a class-like object
  4. Write a generic identity function and observe how TypeScript infers T
  5. Explain why () => void allows returning values but () => undefined does not

⚠️ Common Mistakes

  • Confusing the overload signatures with the implementation — the implementation signature is NOT callable directly; only the overload signatures are visible to callers

  • Thinking () => void means 'returns undefined' — void means the return value is IGNORED, not that it must be undefined. Callbacks typed as void can return anything

  • Forgetting that optional parameters must come after required ones — (a?: string, b: number) is invalid

  • Not typing this in callbacks that depend on context — leads to runtime errors when this is the wrong object

  • Over-using overloads when a union parameter or generic would be simpler — overloads should be a last resort for complex input/output mappings

💼 Interview Questions

🎤 Mock Interview

Practice a live interview for Functions, Overloads & Typing Patterns