Course contentsShow
← TypeScript
Lesson 988 of 1,79623. Type AssertionsFree lesson

Const Assertions with as const

Use `as const` to tell TypeScript to infer the narrowest possible literal types for an expression.

Const Assertions with as const

What you'll learn: How to use as const to lock TypeScript into inferring the narrowest, most specific literal types instead of widening to general primitives.

The Widening Problem Revisited

By default, when you declare variables with let, TypeScript widens literal values to their broader primitive types. This is usually helpful for mutable variables, but sometimes you want TypeScript to remember the exact value:

let status = "pending"; // Type: string (not "pending")

You've learned you can prevent this with explicit annotations or const, but as const offers a more powerful solution—especially for objects and arrays.

What as const Does

The as const assertion tells TypeScript: "Treat this value as deeply immutable and infer the narrowest possible types."

Think of it like freezing a snapshot in time. Instead of saying "this is some string," you're saying "this is specifically the string 'pending' and it will never change."

let status = "pending" as const; // Type: "pending"

Why This Matters

Without as const, objects and arrays get inferred as mutable with wide types:

const config = {
  api: "https://example.com",
  timeout: 5000
};
// Type: { api: string; timeout: number }

With as const, everything locks down:

const config = {
  api: "https://example.com",
  timeout: 5000
} as const;
// Type: { readonly api: "https://example.com"; readonly timeout: 5000 }

Now config.api is typed as the literal "https://example.com", not just string, and all properties become readonly.

Arrays Become Tuples

Without as const, arrays are inferred as mutable arrays:

const colors = ["red", "green", "blue"];
// Type: string[]

With as const, you get a readonly tuple with literal types:

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

Key Takeaway: Use as const when you need TypeScript to remember exact literal values and treat data as deeply immutable—perfect for configuration objects, constant arrays, and enum-like patterns.