Skip to the workspace
Pebellslearn by building
Assertions and Type Compatibility  ›  Lesson

as any and as const

as const 12 minas any switches type checking off for a value, while as const locks a value down to its narrowest, read-only literal type.

typescript / as any and as const

Explore each scene at your own pace.

01 · The rule

The rule

as any and as const

as any switches type checking off for a value, while as const locks a value down to its narrowest, read-only literal type.

Compare disabling checks with preserving literal types and readonly properties.

Two assertions look alike and do opposite things. as any tells the compiler to stop checking a value. as const tells it to check the value more precisely. One should be rare, the other you will reach for often.

The rule

as any switches checking off; as const locks values down.

as any turns a value into type any, which allows every operation:

const data = response as any;
data.tasks.map((t: any) => t.titel.toUpperCase()); // compiles

The typo titel sails through, and so would calling something that is not a function. Checking resumes only when the value is assigned to something with a real type. as any is an escape hatch for moments when the types are genuinely wrong or unavailable. It spreads quietly, so keep it rare and local, and prefer unknown (covered in the last section) when you just do not know the type yet.

as const is a const assertion. It makes the compiler infer the narrowest type it can:

const statuses = ["todo", "doing", "done"] as const;
// type: readonly ["todo", "doing", "done"]

statuses[0];          // "todo", not just string
statuses.push("x");   // error: readonly

const defaults = { status: "todo", done: false } as const;
// type: { readonly status: "todo"; readonly done: false }

Three effects, all at once:

  1. Literal types — "todo" stays "todo" instead of widening to string.
  2. readonly — properties and elements cannot be reassigned.
  3. Tuples — an array literal becomes a fixed, read-only tuple.

A handy pattern: build a union type from a constant list, so the values exist at runtime and as a type:

type Status = (typeof statuses)[number]; // "todo" or "doing" or "done"

Like every assertion, both are erased: the output JavaScript is the same as without them.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.