TypeScript Literal Types
TypeScript Literal Types: Locking Variables to Exact Values
A literal type narrows a broad primitive like string or number down to one exact value, such as "north" or 200. On their own, single literal types look strict, but combining them into unions creates crisp, self-documenting APIs with zero runtime overhead.
Instead of accepting any arbitrary string for an alignment or HTTP method, literal unions catch typos like "centr" immediately in your editor.
String, Numeric, and Boolean Literal Unions
You can combine string literals, numeric literals (like HTTP status codes or dice rolls), and boolean literals cleanly.
type Alignment = "left" | "center" | "right";
type DiceFace = 1 | 2 | 3 | 4 | 5 | 6;
function alignBox(text: string, align: Alignment): string {
return `[${align.toUpperCase()}] ${text}`;
}
function rollFixed(): DiceFace {
return 4;
}
console.log(alignBox("Header", "center"), rollFixed());
Literal Inference Inside Objects with as const
When passing an object field into a function expecting a literal type, const opts = { align: "center" } fails because TypeScript widens opts.align to string. Fix it with as const (const opts = { align: "center" } as const) or annotate const opts: { align: Alignment } = { align: "center" }.
Common Mistakes to Avoid
- Passing
letvariables to literal parameters:let dir = "left";widens tostring, so passingdirtoAlignmentfails unless declared withconstor typed: Alignment. - Duplicating literal unions across multiple files: Export one shared
type Alignment = ...or derive the type from aconst ALIGNMENTS = ["left", "center", "right"] as constarray (typeof ALIGNMENTS[number]) so runtime validation and types never drift. - Confusing
trueliteral type withboolean: Typing a fieldok: trueinside a discriminated union means that branch only matchesok === true.
Frequently Asked Questions
How do I get both a runtime array of options and a literal union type without duplicating?
Write const SIZES = ["sm", "md", "lg"] as const; type Size = (typeof SIZES)[number];. You get autocomplete for "sm" | "md" | "lg" plus the runtime SIZES array for <select> dropdowns.
Are literal types faster or lighter than TypeScript enums?
Yes. Literal unions emit zero runtime JavaScript code, whereas standard enums emit lookup objects.
Can I combine literal types with template literals?
Yes. type EventName = on${Capitalize<"click" | "hover">}`` produces "onClick" | "onHover" automatically.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.