What are union, intersection, keyof and typeof?
Try code in the playgroundUnderstand the concept
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.
Important ideas
-
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.
Can you explain it without the notes?
What are union, intersection, keyof and typeof?
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
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.
Turn this concept into a clear answer.
- 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?”. Examples are study fragments; framework behavior can depend on your version.