Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

TypeScript as const: Const Assertions, Readonly Tuples, and Literal Types

What as const actually changes in inference, why object properties widen without it, and how readonly tuples, derived unions, and satisfies combine in real config and route tables.

~4 min readTypeScript
#TypeScript#Type System#Web Development
3D illustration of mutable TypeScript variable boxes locking into frozen crystalline readonly type blocks with glowing padlocks

as const is a compile-time instruction, not a runtime conversion: it tells TypeScript to infer the narrowest possible type for an expression, keeping literal values instead of widening them to string, number, or boolean, and applying readonly to every object property and array element it touches. The emitted JavaScript is identical to the input, which is exactly why the assertion is cheap and why its effects disappear the moment a value crosses into a context that widens it again.

Quick Summary

  • Without the assertion, const status = "draft" infers "draft", but let infers string, and an object property infers string even when the object is const — the property is mutable, so the compiler widens it.
  • as const on an object marks every property readonly and keeps literal types recursively, including nested objects and arrays.
  • On an array it produces a readonly tuple: fixed length, per-element literal types, no push, no sort, no index assignment.
  • as const only applies to literal expressions. foo as const on a variable or function call is rejected; foo as const on an enum member or template literal type is fine.
  • The assertion cannot be combined with an explicit type annotation on the same declaration — the annotation wins and the assertion is either redundant or an error.
  • satisfies validates a value against a type while preserving the narrow inferred type, which is the combination most real code wants: check the shape, keep the literal.
  • Nothing about as const survives at runtime; there is no freeze, no copy, and no runtime type tag.

Basic syntax and type signatures

typescript
// Widening without the assertion. const a = { mode: "dark" }; // { mode: string } const b = { mode: "dark" } as const; // { readonly mode: "dark" } // Arrays: mutable array of literals vs readonly tuple. const c = ["small", "medium", "large"]; // string[] const d = ["small", "medium", "large"] as const; // readonly ["small", "medium", "large"] // Nested structures narrow recursively. const config = { retries: 3, endpoints: ["https://api.example.com"], flags: { beta: true }, } as const; // { // readonly retries: 3; // readonly endpoints: readonly ["https://api.example.com"]; // readonly flags: { readonly beta: true }; // } // Tuple indexing and derivation follow from the literal types. type Size = (typeof d)[number]; // "small" | "medium" | "large" function pick(size: Size) { /* ... */ } pick("medium"); // ok // pick("huge"); // error: Argument of type '"huge"' is not assignable to type 'Size' // Const assertion on a template literal produces a template literal type. const key = `user:${42}` as const; // "user:42"

The typeof d[number] pattern is the standard way to derive a union from a constant list, and it depends entirely on the tuple produced by the assertion: without it, typeof d[number] is just string.

Comparison of the narrowing tools

ExpressionInferred typeMutableValidatesRuntime effect
const x = "a""a"no (binding)nonone
let x = "a"stringyesnonone
const o = { k: "a" }{ k: string }yesnonone
const o = { k: "a" } as const{ readonly k: "a" }nononone
const a = ["a"] as constreadonly ["a"]nononone
const o = { k: "a" } satisfies Shape{ k: "a" } if Shape allowsyesyesnone
Object.freeze({ k: "a" })Readonly<{ k: string }>nonofreeze
enum E { A = "a" }E.Anonoobject emitted

The row that matters most is the object case: const on a binding does not make properties readonly, so the property type widens. as const is the only syntax that stops that widening for a nested structure, and satisfies is the only one that also checks the shape.

Practical edge cases and deep dives

1. Deriving a union and an exhaustive lookup from one constant list

typescript
export const LOG_LEVELS = ["debug", "info", "warn", "error"] as const; export type LogLevel = (typeof LOG_LEVELS)[number]; const weights: Record<LogLevel, number> = { debug: 10, info: 20, warn: 30, error: 40, }; // The array and the type cannot drift apart, and adding a level // produces a compile error in `weights` instead of a silent gap. export function isLogLevel(value: string): value is LogLevel { return (LOG_LEVELS as readonly string[]).includes(value); }

Without as const, LogLevel would be string, Record<LogLevel, number> would accept any key, and isLogLevel would narrow to a useless type. The cast to readonly string[] inside the predicate is necessary because includes on the tuple type accepts only the four literals, which a plain string argument is not.

2. Reading as const values that arrive from a typed context

Objects asserted as const are deeply readonly, and that propagates into every consumer. A component that accepts the object and mutates a field will not compile, nor will a function that expects a mutable array.

typescript
const ROUTES = [{ path: "/", name: "home" }, { path: "/blog", name: "blog" }] as const; type Route = (typeof ROUTES)[number]; // readonly objects // Copy to a mutable structure when a library requires one. const mutable: Array<{ path: string; name: string }> = ROUTES.map((r) => ({ ...r })); // Spread of a readonly tuple produces a mutable array of the union of its element types. const names: string[] = [...ROUTES.map((r) => r.name)];

ROUTES.map((r) => ({ ...r })) returns objects whose properties are still readonly in the inferred type only because the source properties were readonly; assigning to an explicitly mutable target array widens them back, which is the point of the annotation. Passing the readonly array straight to a function typed Array<T> fails with The type 'readonly [...]' is 'readonly' and cannot be assigned to the mutable type '...' — the fix is a copy at the boundary, not a cast on the declaration.

3. as const versus satisfies on configuration objects

typescript
type RouteConfig = Record<string, { path: string; method: "GET" | "POST" }>; // (a) as const only: narrow literals, but no shape check. const a = { users: { path: "/users", method: "GET" }, bad: { path: 1 } } as const; // (b) annotation only: shape check, but every method widens to the union. const b: RouteConfig = { users: { path: "/users", method: "GET" } }; // (c) satisfies: shape check and literal preservation. const c = { users: { path: "/users", method: "GET" } } as const satisfies RouteConfig; type Keys = keyof typeof c; // "users" const method = c.users.method; // "GET", not "GET" | "POST"

Case (a) compiles even with path: 1, which is why as const alone is not a validation tool. Case (b) catches the mistake but loses the literal type, so c.users.method cannot be used to discriminate anything. Case (c) is the pattern to prefer for route tables, feature flags, and event maps.

4. as const inside generic inference and keyof

typescript
function defineEvents<T extends Record<string, { payload: unknown }>>(events: T) { return events; } const events = defineEvents({ created: { payload: null as null }, updated: { payload: { id: "" as string } }, } as const); type EventName = keyof typeof events; // "created" | "updated" type CreatedPayload = (typeof events)["created"]["payload"]; // null

Here the assertion is what keeps EventName a union of two names instead of string. Without it, T is inferred as Record<string, ...> and the keys collapse. A generic parameter constrained by Record<string, ...> does not force literal key inference on its own; the assertion at the call site is what does.

5. The as const object as a type-level enum replacement

typescript
const Status = { Idle: "idle", Loading: "loading", Failed: "failed", } as const; type Status = (typeof Status)[keyof typeof Status]; // "idle" | "loading" | "failed" function render(status: Status) { switch (status) { case Status.Idle: return "…"; case Status.Loading: return "…loading"; case Status.Failed: return "failed"; } }

This pattern gives the ergonomics of a string enum (Status.Idle reads as a named member) without emitting an enum object, and the string values remain plain strings in JSON and in the DOM. The one cost is that a consumer can still pass the raw literal "idle" where Status.Idle was expected, which is usually desirable and occasionally not.

Common mistakes and compiler errors

Error or symptomCauseFix
A 'const' assertion can only be applied to a 'string', 'number', 'boolean', 'array', or 'object' literalas const applied to a variable, call result, or functionassert the literal at its creation, or use as const satisfies T
Cannot assign to 'x' because it is a read-only propertythe object literal was asserted, so properties are readonlycopy ({ ...obj }) or drop the assertion
The type 'readonly [...]' is 'readonly' and cannot be assigned to the mutable typereadonly tuple passed to an Array<T> parametercopy with [...arr] or change the parameter to readonly T[]
push / sort / splice missing on an arraythe array became a tupledeclare readonly T[] if the type need not be a tuple
'string' is not assignable to type '"small"'the assertion was omitted somewhere and the union widenedderive the union with (typeof arr)[number] and assert the array
Argument of type 'string' is not assignable in includesincludes on a tuple accepts only its member literalswiden first: (arr as readonly string[]).includes(value)
A 'const' assertion cannot be used with an explicit type annotationconst x: T = ... as constchoose as const satisfies T instead
Literal types disappear after a function boundarythe parameter is not generic, so the argument widensuse a generic parameter with extends plus as const at the call site

The single habit that prevents most of these is to decide where the literal type needs to live. If it is only needed inside the module that declares the constant, a plain const with a narrow annotation is enough. If it is needed by other modules — as a union, a key set, or a discriminant — put as const on the declaration and export the derived type, not the literal type written by hand.

Try matching browser tools

All tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.