Question presented to candidate: "What is a discriminated union in TypeScript? Model shapes, or a request that can be loading, successful or failed, and show how the compiler knows which fields are available in each case."
What a strong answer should cover:
- A union of object types that all share one property (the discriminant or tag) whose type is a different literal in each member
- Checking the tag (
switch (s.kind),if (r.ok)) narrows the whole object, so member-specific fields become available - Why it is better than one object with many optional fields: impossible states cannot be written, and excess-property checks reject mixed objects
- The tag must be a literal type (string, number, boolean literal,
undefined); a plainstringtag narrows nothing - Narrowing also works through destructured tags and checks stored in a
const(4.4 / 4.6), and the pattern enables exhaustiveness checking - Typical uses: reducer actions,
Resulttypes, API response states, AST nodes
Code / implementation expected: Yes β define a small discriminated union and a function that switches on the tag.