TypeScript·Intermediate·Coding·1 min read
What is a discriminated union?
Short interview answer
It is a union whose members share a property with distinct literal values. Checking that discriminator narrows the value to one member, exposing only the fields valid for that state.
Example
type Result = | { status: 'ok'; data: string } | { status: 'error'; message: string };
function handle(r: Result) { if (r.status === 'ok') return r.data; // 'message' not available return r.message; // 'data' not available}Key takeaway
Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.