Skip to the page

TypeScript in real projects · mid

Typing functions, overloads and this

Function types describe parameters and return values; overloads give several call signatures for one implementation; optional and rest parameters, and callback typing, catch most real bugs.

The notes

What you must know

  • Function type: type Handler = (e: Event) => void. Optional params (a?: string), rest (...xs: number[]).
  • Overloads: list signatures above one implementation signature; callers only see the overloads. Often a union or generic is simpler.
  • A callback returning a value where void is expected is allowed (so arr.forEach(x => list.push(x)) works).
  • this can be typed as a first fake parameter: function f(this: HTMLElement) {}.

The red pen

Common traps: mistake → fix

  • Mistake: "overloads are checked against each other"

    Fix: the implementation must be compatible, but callers can't call it directly.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you type a callback prop?
  2. When are overloads better than a union parameter?
  3. Why can a function returning number be passed where void is expected?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview