FRONTENDO
Emberhold Forge
0
0
TypeScript · Advanced TypeScript
New technique

Narrowing, all the ways

A master smith reads the metal before striking. TypeScript reads your checks the same way.

TypeScript follows your ifs and returns (control flow analysis) and narrows a union in each branch. Each kind of check narrows a different kind of type.

Watch out: typeof null is "object", so check for null separately. And the in operator only works on objects, so prove something is a non-null object before you ask what's in it.

function describe(x: string | number[] | Date | null) {
  if (x === null) return "nothing";       // x: null
  if (typeof x === "string") return x;    // x: string
  if (Array.isArray(x)) return x.length;  // x: number[]
  return x.toISOString();                 // x: Date
}
  • x instanceof Date narrows to objects made by a class.
  • "swim" in pet narrows to the union members that have a swim property.
  • Under strict, the variable in catch (err) is unknown: JavaScript can throw anything, even a string. Check err instanceof Error before reading err.message.