as const Assertions

Freeze a literal into its narrowest, deeply readonly type instead of letting it widen.

By default TypeScript widens literals: let mode = "dark" becomes string, and an array becomes a mutable string[]. A const assertion β€” as const β€” tells the compiler to keep the value exactly as written: literal types, readonly everything, tuples instead of arrays.

const point = [10, 20] as const;
// type: readonly [10, 20]  (a tuple, not number[])

const theme = { color: "blue" } as const;
// theme.color has type "blue", and is readonly

Why it matters

It is the cleanest way to derive a union of allowed values from data you already have. Combine as const with a typeof index access and your single source of truth is the array itself.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A list of allowed HTTP methods is frozen with as const so the array type is readonly ['GET', 'POST'] instead of string[].
  • An icon map uses as const so each key maps to a specific literal string path, not a generic string.
  • A config object uses as const to prevent any module from accidentally mutating shared startup settings.

More examples

as const on an object

as const freezes the object so each value becomes a string literal type, enabling precise union types via keyof and typeof.

Example Β· ts
const COLORS = {
  red:   '#ff0000',
  green: '#00ff00',
  blue:  '#0000ff',
} as const;

// COLORS.red is '#ff0000', not string
type ColorKey = keyof typeof COLORS;     // 'red' | 'green' | 'blue'
type ColorVal = typeof COLORS[ColorKey]; // '#ff0000' | '#00ff00' | '#0000ff'

as const on an array

Freezes an array so typeof METHODS[number] produces a precise union of the literal string values.

Example Β· ts
const METHODS = ['GET', 'POST', 'PUT', 'DELETE'] as const;
type Method = typeof METHODS[number]; // 'GET' | 'POST' | 'PUT' | 'DELETE'

function isMethod(value: string): value is Method {
  return (METHODS as readonly string[]).includes(value);
}

Derive enum-like type from const

Uses as const with keyof typeof to derive a union type from constant values, replacing string enums with plain objects.

Example Β· ts
const STATUS = {
  PENDING: 'pending',
  ACTIVE:  'active',
  CLOSED:  'closed',
} as const;

type Status = typeof STATUS[keyof typeof STATUS];
// 'pending' | 'active' | 'closed'

function isActive(s: Status): boolean {
  return s === STATUS.ACTIVE;
}

Discussion

  • Be the first to comment on this lesson.
as const Assertions β€” TypeScript | SoundsCode