TypeScript Foundations · 9 min read · Intermediate
Unions, Literal Types & Narrowing
Model exact states with discriminated unions and narrow types safely using typeof and switch.
What you'll learn
- Restrict values to exact literal unions like 'idle' | 'loading' | 'done'
- Build discriminated unions with a shared kind or status tag
- Narrow union types automatically inside if and switch branches
Discriminated unions are one of TypeScript’s superpowers. By giving each variant in a union a literal tag (like status: "ok" vs status: "error"), TypeScript automatically narrows which properties exist inside each if or switch branch.
Fill-in-the-Blank Exercise
Discriminated Union Narrowing
Define a union of Ok and Err using | and check res.ok to narrow.
type ApiResult = { ok: true; data: string } { ok: false; error: string };
function printResult(res: ApiResult) {
if (res.) console.log(res.data);
else console.log(res.error);
}Live Code Lab
TypeScriptnarrowing.ts
Expected OutputClick “Run Live” to compile with TypeScript 5.6
Loaded 12 items Error: Timeout
Check Your Understanding
Score: 0 / 1
1. Why are discriminated unions preferred over multiple boolean flags like isLoading and isError?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.