Literal types, tuples and enums
TypeScript can be much more precise than "any string" or "any array". These tools let you say exactly which values are allowed.
Literal types
A literal type is a single exact value. Combine literals with | to create a fixed set of allowed values:
This is far safer than accepting any string and hoping callers spell it right.
const and literal inference
as const plus typeof X[number] is a popular trick: you write the list once and get both a runtime array (for dropdowns or validation) and a type.
Template literal types
Build string types from other types:
Tuples: fixed-length arrays
A tuple is an array with a known length and a known type at each position:
Enums
Enums define named constants. They're one of the few TypeScript features that generate runtime code:
Open "View the compiled JavaScript" to see the object that the enum becomes.
Should you use enums?
Many TypeScript teams prefer literal unions or as const objects instead:
| String enum | Literal union | as const object |
|
|---|---|---|---|
| Runtime value | ✓ | ✗ | ✓ |
Plain strings accepted ('pending') |
✗ (must use Status.Pending) |
✓ | ✓ |
Works with "type-stripping" tools (Node's built-in TS support, erasableSyntaxOnly) |
✗ | ✓ | ✓ |
Avoid numeric enums (
enum Dir { Up, Down }). They accept any number, which undermines type safety.
Practice
- Create a
Weekdayliteral union and a functionisWeekend(day: Weekday): boolean. - Create a tuple type
RGBof three numbers and a functiontoHex(color: RGB): string. - Create
const SIZES = ['S', 'M', 'L', 'XL'] as constand derive aSizetype from it.
1.What type does const status = 'active' have?
2.What does as const do to an object literal?