TypeScript · Narrowing and unions

Union type

A value that may be one of several types. Narrow before calling type-specific methods.

Syntax
string | number

Example

Example
function print(value: string | number) {
  console.log(typeof value === "string" ? value.toUpperCase() : value.toFixed(1));
}

More in this group

Assertion function Discriminated union Exhaustive switch in operator instanceof guard Non-null assertion Type assertion Type predicate

Learn this in the course

Reference pages are the quick answer. The course explains the why, shows the full example and ends with a challenge.

Open the course