as const on Objects
You'll learn: How to lock down object properties as readonly and preserve their exact literal types using as const.
The Problem Without as const
When you create an object literal, TypeScript widens the types of its properties to be general and mutable:
const config = {
mode: "development",
port: 3000
};
// Type inferred as:
// { mode: string; port: number }
config.mode = "production"; // ✓ Allowed — mode is a mutable string
Notice how "development" became string and 3000 became number. TypeScript assumes you might reassign these properties later.
Using as const on Objects
Adding as const after an object literal does two things simultaneously:
- Makes all properties readonly — you can't reassign them
- Preserves literal types —
"development"stays"development", notstring
const config = {
mode: "development",
port: 3000
} as const;
// Type inferred as:
// { readonly mode: "development"; readonly port: 3000 }
config.port = 8080; // ✗ Error: Cannot assign to 'port' because it is read-only
Deep Readonly Effect
Unlike the readonly modifier you learned earlier, as const applies recursively to nested properties:
const settings = {
database: {
host: "localhost",
port: 5432
}
} as const;
settings.database.host = "prod.db"; // ✗ Error: read-only
// Both levels are locked down
When to Use This
Use as const on objects when you want immutable configuration, lookup tables, or constant data that should never change and where preserving exact values matters for type safety.
Key Takeaway: as const on objects makes all properties deeply readonly and preserves their literal types instead of widening them to general primitives.