×

typescript · level 3 · unit 1 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Overloads give one function several honest descriptions.

Some functions behave differently depending on what you give them. double(21) should hand back a number, but double("ha") a string. A union return type would make every caller check which one they got.

Overloads fix that. Write several signatures, each a heading with no body, then one that handles them all. Callers only see the signatures, so each call gets exactly the right return type.

The implementation's own heading must cover every , but it stays hidden. If no signature matches a call, the checker reports TS2769.

function double(value: number): number;
function double(value: string): string;
function double(value: number | string): number | string {
  if (typeof value === "number") {
    return value * 2;
  }
  return value + value;
}
const n: number = double(21);
const s: string = double("ha");
console.log(n, s);

Overload signatures sit directly above the implementation, with nothing in between.