"a" | "b" Literal Types
Last updated: 2026-10-22
"a" | "b" Literal Types
Literal types promote a value into a type: "up", 1 and true are all types. Alone they are niche, but combined into unions they pin down exact allowed values.
| Group | Type Composition |
|---|---|
| Kind | Type |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
type Size = "small" | "medium" | "large";
let size: Size = "medium";
const mode = "dark"; // const infers the literal type "dark"
let level = 3; // let infers the widened number
⚙️ Parameters
| "a" | 42 | true | Three primitive literal kinds work as types: "a", 42, true |
|---|---|
| as const | Locks object/array members to literal types — handy for config constants |
Returns:None — literal types are type-level only and disappear after compilation.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
up x2 right x1
(Runtime output after transpilation; move("Up", 1) is a compile error — literals must match exactly, case-sensitively)
💡 Notes
ℹ️ Info let widens to string; const keeps the literal type ("dark") — the most common way literal types arise.
💡 Tip Add as const to config constants: every member becomes a literal type, ready to feed literal-union parameters.
⚠️ Note Literal matching is exact and case-sensitive: "Up" does not fit "up", and neither does extra whitespace.
🏷️ Related Type Composition
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q Why does const yield a literal type while let yields string?
A A const never changes, so TS keeps the most precise "value as type"; a let may receive other strings, so it widens to string. Narrow it with an annotation or as const when needed.
Q What does as const do?
A It asserts the deepest readonly form: members become literal types and non-writable. { method: "GET" } infers { method: string }; with as const, method is exactly "GET".
Q Literal unions vs enums?
A Literal unions cost nothing at runtime and interoperate with plain strings; enums add a namespace and reverse mapping. Literal unions suffice for most value domains (see the enum entry).