Union Types

Allowing a value to be one of several different types.

TypeScript3 min readConcept 10 of 54

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.

type ID = string | number;

function printId(id: ID) {
console.log(id);
}

// TS checks if the argument matches either 'string' OR 'number'
printId("abc");

Compile Success

A string satisfies the union because it matches at least one of the allowed types.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1If you have a variable typed as 'A | B', what properties are you allowed to access on it immediately?

Remember this

  • A Union Type (A | B) means a value can be type A OR type B.
  • 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.