Sub topic 8
Assigning to and from Unions and Intersections
Assume you know basic TypeScript syntax, interfaces, type aliases, functions, arrays, and common compiler errors. This chapter focuses on how unions and intersections affect assignability.
Unions: one of several possibilities
A union type uses |. It represents values that belong to at least one of its member types.
type Status = "loading" | "success" | "error";
const current: Status = "loading";
const text: string = current; // Every Status member is a string
let value: string = "success";
// const status: Status = value; // Error: string might be another valueA source value can be assigned to a union target when it is assignable to at least one member. A general string cannot be assigned to Status, because it might contain "cancelled".
When reading a union, TypeScript exposes only what every member guarantees:
function describe(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}The typeof check narrows the union. Before the check, methods specific to only one member are unavailable.
Intersections: all requirements at once
An intersection type uses &. It combines the requirements of multiple types.
interface Readable {
read(): string;
}
interface Writable {
write(value: string): void;
}
type Stream = Readable & Writable;
const stream: Stream = {
read: () => "data",
write: (value) => console.log(value),
};A source assigned to Stream must satisfy both Readable and Writable. Reading a Stream gives access to both sets of members.
An intersection can become impossible when its requirements conflict:
type TextValue = string & number;
// TextValue has no possible valueFor object properties, incompatible primitive types often reduce the property to never, a type with no values.
Widening and preserving union members
Literal values often widen when stored in mutable variables or object properties.
type Mode = "fast" | "slow";
const fixed = "fast";
const mode1: Mode = fixed; // OK
const config = { mode: "fast" };
// const mode2: Mode = config.mode; // Error: config.mode is string
const config2 = { mode: "fast" } as const;
const mode3: Mode = config2.mode; // OKas const preserves the literal type and makes the object readonly. Use it when a value must remain a specific union member.
Exercise
Why can "fast" be assigned to ("fast" | "slow"), but a general string cannot?
Show answer
The literal "fast" is one known member of the union. A general string might contain a value outside the union.