Extracting Union Members as Values
What you'll learn: How to use a single const array with as const and typeof to create both runtime values and a compile-time union type from one source of truth.
The Problem: Duplication
You often need the same string literals in two places:
- At runtime — as values in an array for looping, validation, etc.
- At compile-time — as a union type for parameters or variables.
Maintaining both separately is error-prone. Add a new status? You must update two places.
The Solution: Derive the Union from the Array
With as const and typeof, you can define the array once and extract the union type from it:
const STATUSES = ['pending', 'active', 'archived'] as const;
type Status = typeof STATUSES[number];
// Status = 'pending' | 'active' | 'archived'
Breaking It Down
as const— Makes the array readonly and infers each element as a literal type (notstring[]).typeof STATUSES— Gets the type of the array:readonly ['pending', 'active', 'archived'](a tuple).[number]— Accesses all numeric indices, extracting the union of all element types.
Now you have:
- Runtime values in
STATUSESfor iteration or validation. - Compile-time type
Statusfor parameters and variables.
function setStatus(status: Status) {
// only accepts 'pending' | 'active' | 'archived'
}
STATUSES.forEach(s => console.log(s)); // Runtime access
Key Takeaway: Use as const arrays with typeof ArrayName[number] to derive union types from runtime values, keeping your types and data in sync with a single source of truth.