Literal Types
In this page:
String Literal Types
A string literal type represents one single, exact string value, such as the type admin rather than the general type string. Combining several string literals with a union, like admin | editor | viewer, creates a controlled, closed set of allowed choices.
Example: String Literal Types
type Role = 'admin' | 'editor';
let role: Role = 'admin';
console.log(role);
Number Literal Types
Number literal types work the same way for numbers, restricting a value to one or more specific exact numbers rather than any number at all. They're especially handy when only a small, fixed set of numeric options is actually valid, like HTTP status codes.
Example: Number Literal Types
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
let roll: DiceRoll = 4;
console.log(roll);
Boolean Literal Types
Boolean literal types can restrict a value to exactly true or exactly false as its own distinct type, rather than the general boolean type that allows either. This is less common day-to-day but can be useful when modeling a specific, fixed object state.
Example: Boolean Literal Types
type AlwaysTrue = true;
let flag: AlwaysTrue = true;
console.log(flag);
Literal Types in Functions
Literal types in function parameters prevent callers from passing any value outside a specific, supported set, catching typos and unsupported options at compile time instead of at runtime. They also give editors enough information to offer precise autocomplete suggestions for valid values.
Example: Literal Types in Functions
function setAlign(value: 'left' | 'center' | 'right') {
console.log(`Aligned: ${value}`);
}
setAlign('center');
Literal Types with Type Aliases
Pairing a literal union with a type alias, like type Theme = light | dark, makes that set of allowed values reusable across variables, functions, and object properties throughout a codebase. This is a common and effective pattern for representing application states and fixed configuration options.
Example: Literal Types with Type Aliases
type Theme = 'light' | 'dark';
let theme: Theme = 'dark';
console.log(theme);
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: