0Pricing
TypeScript Academy · Lesson

const Assertions and as const

Use as const to infer literal and tuple types precisely.

What Is as const?

as const is a type assertion that tells TypeScript to infer the most specific literal types possible for an expression, and to make all properties readonly.

const colors = ["red", "green", "blue"] as const;
// type: readonly ["red", "green", "blue"]

Preventing Widening with as const

Without as const, string values in arrays and objects widen to string. With it, they stay as their literal types.

const dir1 = { direction: "left" };
// dir1.direction: string

const dir2 = { direction: "left" } as const;
// dir2.direction: "left"

All lessons in this course

  1. Type Widening and Narrowing Mechanics
  2. Contextual Typing: Inference from Context
  3. Freshness and Excess Property Checking
  4. const Assertions and as const
← Back to TypeScript Academy