×

typescript · level 3 · unit 6 · 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

An stops the program when data is wrong.

A type guard answers a question, so you still need an if. Sometimes bad data means there is no point carrying on. An assertion function checks the value and, if it is wrong, uses to stop with an error. If the function returns at all, the value was fine.

Its return type says what it proves: asserts value is number. After the call, the checker treats the value as a number on every line below, with no if needed. Guard when you can recover. Assert when you cannot.

function assertIsNumber(value: unknown, name: string): asserts value is number {
  if (typeof value !== "number") {
    throw new Error(`${name} must be a number`);
  }
}
const reply: unknown = JSON.parse('{"stock": 12}').stock;
assertIsNumber(reply, "stock");
console.log(reply + 1);

new Error("...") makes an error with a message, ready to be thrown.