Course contentsShow
← TypeScript
Lesson 473 of 1,79611. Literal TypesFree lesson

as const vs readonly Modifiers

The relationship between as const and readonly, and when each is appropriate.

as const vs readonly Modifiers

You'll learn: The key differences between as const and readonly, and when each tool is the right choice.

Two Tools, Different Jobs

Both as const and readonly help prevent mutations, but they work at different stages and have different strengths:

  • readonly is a property modifier you add when defining a type or interface. It marks individual properties as unchangeable.
  • as const is a type assertion you apply to values. It locks down an entire value to its most specific literal types and makes everything readonly in one stroke.

Think of readonly like labeling individual drawers in a filing cabinet as "locked," while as const is like sealing the entire cabinet shut.

When to Use Each

Use readonly when:

  • You're defining reusable types or interfaces
  • You want to mark only some properties as readonly
  • You're working with class properties
interface Config {
  readonly apiKey: string; // Can't reassign this
  retries: number;         // Can change this
}

Use as const when:

  • You have a literal value and want maximum specificity
  • You want the entire structure locked down at once
  • You're creating constant data structures
const config = {
  apiKey: "abc123",
  retries: 3
} as const;
// Type: { readonly apiKey: "abc123"; readonly retries: 3 }

The Key Difference

readonly requires you to define the type separately, then apply it. as const works directly on the value itself, inferring the narrowest possible readonly type automatically.

Key Takeaway: Use readonly when defining types with selective immutability; use as const when you want instant, deep literal inference on a value.