Course contentsShow
← TypeScript
Lesson 482 of 1,79611. Literal TypesFree lesson

Extracting Union Members as Values

Use const arrays with 'as const' and 'typeof' to derive both runtime values and union types from one source.

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:

  1. At runtime — as values in an array for looping, validation, etc.
  2. 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 (not string[]).
  • 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 STATUSES for iteration or validation.
  • Compile-time type Status for 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.