Union Types

A union is a value that is one of several types. string | number. Book | null. "loading" | "error" | "ready".

A literal union is a far better tool than loose strings: a typo becomes a compile error rather than a branch that silently never runs. That alone justifies the syntax.

Try it

Fix the typo. Then fix the second error by checking typeof value === "string" first.

loading editor…

checking…

Two errors. The typo is caught, and toUpperCase is rejected because a number does not have it. You may only use members that exist on EVERY branch until you narrow.

✦ strictNullChecks is the setting that matters most

With it on, Book and Book | null are genuinely different types, and you cannot read a property off the second without proving it is not null. That one check catches the single most common runtime error in JavaScript. It is included in strict: true.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Narrowing →
← Back