Course outline · 0% complete

0/26 lessons0%

Course overview →

void, never, and Overloads

lesson 5-3 · ~12 min · 17/26

Two return types for "nothing"

You met void in lesson 3-2: the function finishes normally but returns nothing worth using. console.log returns void.

never is stronger: the function never finishes normally at all. It always throws, or loops forever. No value ever comes back, not even undefined.

function fail(message: string): never {
  throw new Error(message);
}

Why bother? Because the compiler understands the difference. After a call to a never function, code is unreachable, and in a discriminated union switch (lesson 4-3), assigning the leftover case to never proves you handled every member. Forget one and the compiler tells you which.

Code exercise · typescript

Run it. fail is typed never because it always throws. seatLabel still returns string on every normal path, the compiler accepts the fail branch because nothing survives it.

Code exercise · typescript

The exhaustiveness pattern from the text, live. In the default branch every union member has been handled, so cmd has been narrowed to never — nothing is left — and assigning it to a never variable compiles. Run it, then add a third member { kind: "double" } to Command without adding a case: the never line becomes a compile error naming the forgotten member.

Quiz

Which return type fits a logEvent function whose body is a single console.log call and a normal end?

Overloads, the lightweight way

Sometimes one function accepts several input forms. Full TypeScript overloads list multiple signatures above one implementation:

function len(x: string): number;
function len(x: string[]): number;
function len(x: string | string[]): number {
  return x.length;
}

Callers see the two precise signatures, the implementation handles the union. In practice, most code does not need this ceremony: a plain union parameter plus narrowing (Unit 4) covers the majority of cases, and unions should be your first reach. Recognize overload syntax when you read library code, write it only when a union genuinely cannot express the input-output relationship.

Problem

A function's entire body is: throw new Error("nope"). What is its most precise return type? (one word)