What are union, intersection, keyof and typeof?
Practice this questionWANT TO UNDERSTAND THE CONCEPT FIRST?Learn What are union, intersection, keyof and typeof?
Definition:
A union allows a value to match one of several types, while an intersection requires it to satisfy all included types. keyof extracts property names from a type, and TypeScript's type-position typeof derives a type from a value declaration. Together they help express safe property access and reusable contracts.
Key points:
-
A | B: either type.A & B: must satisfy both types. -
keyof Usergives the property names of theUsertype. -
type User = typeof usergets a type from a value; runtimetypeof userreturns a string. -
For a union, narrow the value before using members that are not present on every possibility.
-
An intersection of incompatible property requirements can produce an impossible type such as
never.
Interview point:
- Runtime
typeofreturns a string; type-positiontypeofis a compile-time type query. They solve different problems.
Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “What are union, intersection, keyof and typeof?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.