TypeScript Developer interview question · Most asked
What are discriminated unions and why are they powerful?
Summary
A discriminated (tagged) union is a union of object types sharing a literal property (the discriminant, e.g., type or status). Checking that property narrows to the exact variant, and exhaustiveness checks ensure every case is handled.
Longer Answer
They model state machines and API results precisely, making invalid states unrepresentable (e.g., { status: 'success'; data } vs { status: 'error'; error } instead of optional data? and error?). Combined with never-based exhaustiveness checks, adding a variant forces updates everywhere.
Code Example
type Result<T> =
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: Error };
function render(r: Result<string[]>) {
switch (r.status) {
case "loading": return "Loading…";
case "success": return r.data.join(", ");
case "error": return r.error.message;
default: {
const _exhaustive: never = r;
return _exhaustive;
}
}
}
Key Points
- Shared literal tag field
- Narrowing per variant
- Exhaustiveness via
never - Make invalid states unrepresentable
More most-asked TypeScript Developer questions
- What is TypeScript and what problems does it solve?
- What are the differences between `interface` and `type` aliases?
- Explain `any`, `unknown` and `never`.
- What is type narrowing and what techniques does TypeScript support?
- What are generics and how do constraints work?
- Which built-in utility types do you use most, and what do they do?
- What is structural typing in TypeScript?
- What are mapped types? Show how `Partial` or `Readonly` could be implemented.