Skip to main content

Unions and Intersections

TypeScript allows you to elegantly compose complex types natively by combining simple types together utilizing Unions and Intersections.

1. Union Types (|)

A Union Type dictates that a value can be exactly ONE of several distinct types. We use the vertical bar | to separate each allowed type.

// ID can be EITHER a string OR a number legally!
function printId(id: string | number) {
// Note: Before we can run Number or String specific methods on 'id',
// we must first "narrow" it to prove to TS what type it successfully is!

if (typeof id === "string") {
console.log(id.toUpperCase());
} else {
console.log(id);
}
}

printId(101); // Valid
printId("202_X"); // Valid
// printId(true); // ERROR! Boolean is not allowed in this Union!

Literal Type Unions

You can combine explicit rigid strings or numbers together securely into highly strict dropdowns.

type WindowStates = "open" | "closed" | "minimized";

const currentWindow: WindowStates = "minimized"; // Legal

2. Intersection Types (&)

An Intersection Type firmly commands that an object MUST contain the merged requirements of multiple types simultaneously. It uses the ampersand &.

type Colorful = { color: string };
type Circle = { radius: number };

// Building the Intersection!
type ColorfulCircle = Colorful & Circle;

// Must successfully satisfy the constraints of BOTH parent models natively
const myShape: ColorfulCircle = {
color: "red",
radius: 42
};

// TS ERROR: Property 'radius' is explicitly missing!
// const badShape: ColorfulCircle = { color: "blue" };