Hone

Lessons · TypeScript · narrowing with checks

Checks the compiler follows

typeof, instanceof, Array.isArray, === null and 'in' inside an if narrow a union to one branch's type.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

This is how TypeScript lets you handle every case of messy data and proves you handled them.

How to think about it

Which odd cases can I rule out first? Check for the odd cases first (null, undefined), return or handle them, then the compiler knows what is left. Each branch gets the narrowed type automatically.

Worked example

function size(x: string | string[] | null): number {
Three possibilities in.
  if (x === null) return 0;
Now x is string | string[].
  if (typeof x === "string") return x.length;
Now string.
  return x.length;
Only string[] is left.
}

Your turn

Narrow to the array case.

if ((x)) return x.map(String);

The trap

Narrowing in one function does not carry into a callback or a later line after reassignment. The compiler tracks control flow, not your intent.

Practise narrowing with checks on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.