Skip to main content
The | operator in TypeScript denotes a Union Type, constructing a new type that represents a value capable of satisfying at least one of several constituent types. In type theory, it functions as an inclusive logical disjunction (OR) at the type level. Because TypeScript utilizes structural typing, a union does not enforce mutual exclusivity (XOR); a value can satisfy multiple constituent types simultaneously. The operator expands the set of permissible values for a given binding while strictly limiting the immediately accessible properties to the intersection of the constituent types’ members.
Type Mechanics and Property Access When the TypeScript compiler evaluates a union type, it enforces strict structural safety. If a variable is typed as A | B, the compiler only permits access to members (properties or methods) that are common to both A and B. Because unions are inclusive, an object containing properties from multiple constituent types is perfectly assignable to the union.
Control Flow Analysis and Narrowing Because the compiler restricts access to shared members, interacting with type-specific members requires type narrowing. TypeScript utilizes control flow analysis to reduce a union type to a specific constituent type within a given lexical scope. This is achieved via type guards (e.g., typeof, instanceof, the in operator, or custom type predicates).
Literal Unions The | operator is frequently applied to literal types (string, number, or boolean literals) to define a finite, discrete set of exact permissible values, effectively creating an enumeration at the type level.
Discriminated (Tagged) Unions A core structural pattern reliant on the | operator is the discriminated union. This occurs when all constituent types in a union share a common, literal-typed property (the discriminant). The compiler uses this discriminant to perform exhaustive type checking and precise narrowing across the union.
Tired of Poor TypeScript Skills? Fix That With Deep Grasping!Learn More