Menu

Overloads and this

Lesson 4: Overloads and this

What are overloads?

Overloads let one function have several call signatures, each with its own parameter and return types.

Approach Use when
Union parameter The return type is the same for every input
Overloads The return type depends on which input was given
Generics (Module 7) The return type follows the input type directly

Example

type Product = { id: string; name: string };

// Overload signatures
function findProduct(id: string): Product | undefined;
function findProduct(ids: string[]): Product[];
// Implementation signature (not visible to callers)
function findProduct(input: string | string[]): Product | Product[] | undefined {
  if (Array.isArray(input)) {
    return catalogue.filter((p) => input.includes(p.id));
  }
  return catalogue.find((p) => p.id === input);
}

const one = findProduct('p1');          // Product | undefined
const many = findProduct(['p1', 'p2']); // Product[]

Typing **this**:

interface CartButton {
  label: string;
  onClick(this: CartButton): void;
}

const button: CartButton = {
  label: 'Add to cart',
  onClick() {
    console.log(this.label); // 'this' is CartButton
  },
};

const handler = button.onClick;
handler();
// Error: The 'this' context of type 'void' is not assignable to method's 'this' of type 'CartButton'.

How it works

  • Callers see only the overload signatures, so they get precise return types.
  • The implementation must handle every overload, but its own signature is hidden.
  • A this parameter is a fake first parameter that is erased in the output. It tells TypeScript what this must be when the function runs.
  • Arrow functions do not have their own this; they use the surrounding one, which is why they are popular for callbacks in classes.

Common mistakes

Mistake Effect Fix
Overloads that could be a single union Extra code to maintain Use a union when the return type does not change
Implementation signature that does not cover all overloads Error Widen the implementation parameters
Passing a method as a callback (setTimeout(cart.save, 0)) this is lost at runtime Use an arrow function or .bind(cart)

Key takeaways

  • Use overloads when the return type depends on the arguments; otherwise prefer unions or generics.
  • Type this explicitly when a function relies on it.

Try it: Write an overloaded formatPrice that returns a string for a number and a string array for an array of numbers.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details