Skip to the solution
MediumFrontend9 min read

What is a discriminated union?

494 views

The problem

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 plain string tag 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, Result types, API response states, AST nodes

Code / implementation expected: Yes β€” define a small discriminated union and a function that switches on the tag.

  • discriminated-union

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptShapes and a Result type: narrowing by a literal tag
TypeScriptReducer actions, destructured tags and literal-only discriminants

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 44 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

How do `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes` and TS 5.6+ checks harden 2025 codebases?

Continue