How can a discriminated union prevent impossible UI states?
Understand the idea, explain it in your own words and use the rubric to find your next learning gap.
The idea behind the question
A discriminant such as status lets TypeScript narrow a union to a specific state shape. This makes required data available only in states where it actually exists.
Separate loading, error and data booleans permit a screen that is simultaneously loading, failed and showing an unrelated success result.
A practical way to learn it
Define a request-state union and render every variant. Add a cancelled variant and use the compiler to locate handling that is no longer exhaustive.
Open TypeScript playgroundThe related tool opens separately; your interview answer stays here. Written practice is self-guided, without automatic code grading.
Build an explanation you understand
- State what the concept does in plain language.
- Apply it to the example and make your assumptions explicit.
- Explain a trade-off, failure case and how you would test it.
- Distinguish your actual experience from a proposed approach.
How would you explain it?
Single-question timers reset on refresh. Full mock sessions can resume from this browser.
Strengthen your explanation
Compare reasoning, not identical wording. Reference answers describe a possible approach; replace hypothetical statements with truthful details from your own work.
One way to answer
I would model distinct idle, loading, success and error variants with a literal status property. Success would require its data and error would require an error message. Rendering can switch on status and use an exhaustive check to catch a newly added variant at compile time. This improves internal correctness but does not validate data arriving from JSON; that boundary still needs runtime checks. I would test transitions and error rendering as user behavior, and avoid type assertions that bypass the guarantees the union is meant to provide.
What a strong explanation should cover
Tick only the points your own answer addresses. This is self-assessment, not AI scoring.
0 / 3 points self-reportedWatch out for
- Casting unvalidated network data to the desired union.
Now go one level deeper
- How would you represent refreshing while keeping old results visible?
- What changes when a new cancelled state is introduced?
Further reading
Further-reading links support learning; the reference is Sukoaa-authored, not an official employer answer key.