Question presented to candidate:
"Explain union and intersection types. When would you reach for A | B versus A & B, and what happens to the members you are allowed to use in each case?"
What a strong answer should cover:
- A union
A | Bmeans the value is one of the types; only members common to every member are usable until you narrow (typeof,in, a tag check) - An intersection
A & Bmeans the value is all of the types at once; it has every property of each part, which is how you compose object types - The counter-intuitive set view: a union of object types allows more values but fewer usable properties; an intersection allows fewer values but more properties
- Incompatible intersections collapse:
string & numberisnever, and a clash on a property makes that property (or, for literal tags, the whole object)never - Unions are not exclusive (
{ x } | { y }accepts an object with both) and&silently producesneverwhereinterface extendsreports a conflict - Practical uses: literal unions and discriminated unions for states, intersections for mixins,
mergehelpers and branded types
Code / implementation expected: Optional β narrow a string | number, and compose two object types with &.