DEV Community

Cover image for "as const" vs "readonly" in TypeScript: What’s the Difference?
Arka Chakraborty
Arka Chakraborty

Posted on

"as const" vs "readonly" in TypeScript: What’s the Difference?

as const vs readonly


Both enforce immutability, but they work at different levels and confusing them can lead to subtle bugs.


🧠Context

Developers often ask: when should I use as const, and when should I use readonly? The answer depends on whether you’re working with values or types.


💡Intro

This post compares both features, shows their differences, and explains when to use each.


Why Use This?

  • as const → literal type + value immutability.
  • readonly → type-level immutability.

📝With vs Without Example

// as const
const roles = ["admin", "user"] as const;
type Role = typeof roles[number]; // "admin" | "user"

Enter fullscreen mode Exit fullscreen mode
// readonly
type Roles = readonly string[];
const roles: Roles = ["admin", "user"];
// Cannot push new items

Enter fullscreen mode Exit fullscreen mode

📌Real Life Use Cases

  • as const for config objects, button variants.
  • readonly for API response types, props contracts.

Think of as const as a value lock, and readonly as a type contract.

Top comments (0)