Advertisement
Advanced TypeScript, Readonly, const Assertions & Immutability

How would you derive a union type of allowed string values directly from a readonly array of literals, using 'typeof' and indexed access together?

Short answer

Combine 'as const' (to get a readonly tuple of literals) with `typeof arrayName[number]` — the `[number]` indexed access extracts the union of ALL element types in the tuple, giving you a derived union type that automatically stays in sync if the array's contents change.

Save TypeScript mock interview
Advertisement
AModel answer
Combine 'as const' (to get a readonly tuple of literals) with `typeof arrayName[number]` — the `[number]` indexed access extracts the union of ALL element types in the tuple, giving you a derived union type that automatically stays in sync if the array's contents change.
const THEMES = ['light', 'dark', 'system'] as const;
type Theme = typeof THEMES[number]; // 'light' | 'dark' | 'system'

function setTheme(theme: Theme) { /* ... */ }
setTheme('dark'); // OK
// setTheme('blue'); // Error: not assignable to Theme
Real-world example
Keeping a runtime array (used for iteration, like populating a dropdown) and its corresponding literal union type automatically in sync from a single source of truth.
Likely follow-ups
  • Why is this pattern generally preferred over maintaining a separate array AND a separate manually-written union type?
Related topics