Literal unions
Concept and syntax
A literal union restricts a value to a finite set of exact alternatives. Unlike string, "idle" | "busy" rejects arbitrary text. Use it for known states or options; incoming untrusted text still needs runtime validation.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
type Mode = "idle" | "busy";function label(m:Mode){ return m === "idle" ? "ready" : "wait"; }console.log(label("idle"), label("busy"));Expected output:
ready waitCommon mistake
Intentionally invalid; compile separately and do not execute.
Expected diagnostic: TS2322. paused is outside the union. Add it only if it is a supported state.
Practice and recap
Add a third mode and decide its label.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Literal unions — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Mode = "idle" | "busy";function label(m:Mode){ return m === "idle" ? "ready" : "wait"; }console.log(label("idle"), label("busy"));Which diagnostic and explanation match the rejected example under the lesson settings?
type Mode = "idle" | "busy";const mode:Mode = "paused";