Literal types
Concept and syntax
A literal type limits a value to one exact literal, such as "draft", 3 or true. A union of literals describes a small permitted set. The variable annotation controls later assignments even when a let binding can change. This is useful for status names and other finite choices. Literal types do not check external strings at runtime; a runtime guard is needed for that.
Working example
Compile standalone examples in a fresh directory with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
let mode: "draft" | "ready" = "draft";mode = "ready";const attempts: 3 = 3;const enabled: true = true;console.log(mode, attempts, enabled);Expected output (one line per log):
ready 3 trueCommon mistake
Intentionally invalid; check this snippet separately. Do not run it.
Expected compiler diagnostic: TS2322. The allowed set does not include archived. Add it only if the actual status model permits it.
Practice and recap
Model a traffic status with three exact string choices. Try one permitted and one unlisted value.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Literal types — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
Which type permits only two exact status strings?
Can a variable annotated 3 hold 4?
Which literal can initialize mode without widening its contract?
let mode: "draft" | "ready" = "archived";