Ad space (banner)
Lesson 10 / 20

Union Types

This lesson covers union types, used to express "one of several possible types." It's for anyone searching "TypeScript union type usage."

Writing TypeA | TypeB expresses "either TypeA or TypeB." For example, number | string means "a number or a string."

The example builds a function, function formatId(id: number | string): string, that checks the actual type with typeof before branching its logic. This pattern โ€” checking a type before branching โ€” is called a type guard.

A common early mistake is calling a method that only exists on one of the possible types directly on a union-typed variable. You need to narrow the type first, with something like typeof or instanceof, before using it.

In real projects, union types are used a lot when an API response can take multiple shapes โ€” like "data on success, an error message on failure."

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run TypeScript directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)