Explain union types, narrowing and discriminated unions.
A union A | B means "one of these". Before you can use members that only one side has, TypeScript makes you narrow the type.
Narrowing techniques
typeof x === 'string',x instanceof Date,'key' in x.- Truthiness and equality checks (
if (x),x === null). - User-defined type guards:
function isCat(a: Animal): a is Cat. - Assertion functions:
function assert(v): asserts v.
Discriminated unions
Give every variant a common literal field (the discriminant, often type or status). A switch on it narrows each branch automatically. Add a never check in default and the compiler errors when someone adds a new variant but forgets to handle it (exhaustiveness checking).
This pattern models UI states much better than several booleans (isLoading, isError, data), which allow impossible combinations.
Example
type RequestState<T> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: string };
function render(state: RequestState<string[]>): string {
switch (state.status) {
case 'idle': return 'Press search';
case 'loading': return 'Loading…';
case 'success': return state.data.join(', '); // data only exists here
case 'error': return `Failed: ${state.error}`;
default: {
const unreachable: never = state; // compile error if a case is missing
return unreachable;
}
}
}Follow-up questions interviewers ask
Try answering each one before you open it.
Why are reducers in React a good fit for discriminated unions?
Actions like { type: 'add'; item: Item } | { type: 'remove'; id: string } narrow by type inside the reducer's switch, so each case gets the correct payload type and dispatch rejects malformed actions at compile time.