Union Types
Allowing a value to be one of several different types.
The OR Operator for Types
In JavaScript, a variable's type can change over time. An ID might be generated as a number by the database, but passed around as a string in the URL.
TypeScript's Union Type (|) allows you to model this reality. It acts like an OR operator for types. string | number means 'this value can be a string OR a number'.
Safety across multiple shapes
Union types are incredibly common when fetching data. An API response is often a union of a loading state, a success state (with data), and an error state (with a message).
By typing the response as a union, TypeScript forces you to handle all possible states before you can safely access the data.
Defining and using unions
You define a union using the pipe character (|).
typescript
type Identifier = string | number;
function printId(id: Identifier) {
console.log("Your ID is: " + id);
}
Try it
Select different values to see how a union type acts as a gatekeeper, accepting valid shapes and rejecting invalid ones.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- A Union Type (
A | B) means a value can be typeAOR typeB. - You can only immediately access properties that exist on ALL members of the union.
- To access specific properties, you must 'narrow' the union type first.
Done with this concept?
Mark it complete to track your progress. No login needed.