Sub topic 3
Readonly objects with literal properties
This chapter covers what as const does to an object literal. You will see how property types change, how the change reaches nested values, and where it stops. It assumes you know the difference between let and const, how literal types such as "a" | "b" work, and why TypeScript widens let x = "left" to string. Arrays and tuples, deriving unions, and satisfies each get their own chapter, so this one only previews them.
The default shape of an object literal
A const declaration stops you from reassigning the variable. It does not stop you from changing the object's properties. TypeScript therefore assumes each property may later hold a different value of the same kind, and it widens each property type:
const server = { host: "localhost", port: 8080, secure: false };
// { host: string; port: number; secure: boolean }
server.port = 9090; // allowed
server.secure = true; // allowedThis default is usually right. If the code really does change port, then number is the correct type. It becomes a problem when the object is meant as a fixed description, such as configuration, a lookup table, or a set of named options. The compiler then forgets the exact values you wrote, and later code that needs those values fails to type-check.
function setMode(mode: "dark" | "light"): void {
console.log(`mode is ${mode}`);
}
const options = { mode: "dark", retries: 3 };
// setMode(options.mode);
// error: Argument of type 'string' is not assignable to
// parameter of type '"dark" | "light"'.The value "dark" is right there in the source. The type of options.mode has already been widened to string.
Adding `as const` to an object
Putting as const after an object literal changes two things for every property:
- The property type is the exact literal you wrote, with no widening.
- The property is marked
readonly.
const server = { host: "localhost", port: 8080, secure: false } as const;
// {
// readonly host: "localhost";
// readonly port: 8080;
// readonly secure: false;
// }
// server.port = 9090;
// error: Cannot assign to 'port' because it is a read-only property.The earlier setMode call now compiles:
function setMode(mode: "dark" | "light"): void {
console.log(`mode is ${mode}`);
}
const options = { mode: "dark", retries: 3 } as const;
setMode(options.mode); // OK: options.mode has the type "dark"The table below summarizes the difference for a single object.
| Source | Type of `mode` | Type of `retries` | Can you assign to `retries`? |
|---|---|---|---|
| `{ mode: "dark", retries: 3 }` | `string` | `number` | Yes |
| `{ mode: "dark", retries: 3 } as const` | `"dark"` | `3` | No, it is `readonly` |
The readonly modifier is a compile-time check only. Nothing in the emitted JavaScript is frozen. The later chapter on restrictions covers this in detail.
The assertion reaches nested values
A const assertion applies to the whole literal expression, including every nested literal. You write as const once, at the outermost level.
const theme = {
name: "midnight",
colors: {
background: "#0b0d17",
accent: "#7aa2f7",
},
breakpoints: [480, 768, 1024],
} as const;
type Theme = typeof theme;
// {
// readonly name: "midnight";
// readonly colors: {
// readonly background: "#0b0d17";
// readonly accent: "#7aa2f7";
// };
// readonly breakpoints: readonly [480, 768, 1024];
// }
const accent = theme.colors.accent; // "#7aa2f7"
// theme.colors.accent = "#ffffff";
// error: Cannot assign to 'accent' because it is a read-only property.Two details are worth noting:
readonlyis applied at every level. Locking the outer object would not by itself lockcolors, but a const assertion does both.- The
breakpointsarray became a readonly tuple,readonly [480, 768, 1024]. This is the array behavior from the next chapter. For now, note that you get it without writing anything extra.
You also get this behavior when the nested literal is an array of objects:
const menu = {
items: [
{ label: "Home", href: "/" },
{ label: "Docs", href: "/docs" },
],
} as const;
const href = menu.items[1].href; // "/docs"Because items is a tuple, index 1 has a known element type. With a plain object, menu.items[1].href would be string.
Applying `as const` to part of an object
You can put a const assertion on a single property value instead of the whole object. Only that property changes:
const partial = { mode: "dark" as const, retries: 3 };
// { mode: "dark"; retries: number }
partial.retries = 5; // allowed: retries is still a mutable number
// partial.mode = "dark"; // allowed too, but only the value "dark" fits the typeNote that mode is not readonly here. The assertion on a primitive literal narrows its type, but readonly comes from asserting the object literal that contains the property. The two effects come from different places:
- Asserting a primitive literal such as
"dark" as constfixes that value's type to"dark". - Asserting an object literal adds
readonlyto its properties and fixes the types of the values inside it.
Use the per-property form when most of an object is genuinely mutable and only one field needs a precise type. Use the whole-object form for configuration and constants.
An alternative: a type annotation
A type annotation also keeps a property narrow, and it can be a better choice when you already have a named type:
type Options = { mode: "dark" | "light"; retries: number };
const options: Options = { mode: "dark", retries: 3 };
// options.mode is "dark" | "light", not "dark"The annotation sets the type to what you declared, which is the wider union. as const records exactly what you wrote. If you want both a check against a declared type and the exact literals, the as const satisfies chapter shows how to combine them.
Values that are not literals stay as they are
A const assertion can only make a literal more precise. If a property's value is a variable or a function call result, as const cannot recover a literal type that the expression does not have.
function load(name: string) {
const user = { name, role: "admin", active: true } as const;
return user;
}
// return type:
// { readonly name: string; readonly role: "admin"; readonly active: true }The properties role and active were literals, so they are narrowed. The property name came from a string parameter, so it stays string, although it is now readonly.
The same applies to shorthand properties that refer to variables. What matters is the type of the variable at that point:
const level = "info";
let channel = "stdout";
const logger = { level, channel } as const;
// { readonly level: "info"; readonly channel: string }level was declared with const and holds the literal type "info". channel was declared with let, so it is a string.
Literal types from `as const` do not widen again
There is one subtle effect on later code. A literal type produced by as const is not widened when you copy it into a mutable variable.
const c = { mode: "dark" } as const;
let m = c.mode; // "dark"
// m = "light"; // error: Type '"light"' is not assignable to type '"dark"'.Compare this with the plain case from the start of the tutorial, where const b = "left" gives b the type "left", but let c = b gives c the type string. A const declaration of a string literal yields a type that is allowed to widen later. A const assertion yields a type that is not. If you copy a value out of an as const object into a let variable and then want to assign other values to it, annotate the variable: let m: string = c.mode;.
Readonly properties and assignability
You might expect that a readonly object cannot be passed where a mutable object type is expected. For object properties, TypeScript does not enforce that:
const fixed = { retries: 3 } as const;
// { readonly retries: 3 }
const loose: { retries: number } = fixed; // compiles
loose.retries = 10; // compiles
console.log(fixed.retries); // prints 10, but its type says 3The readonly modifier on a property blocks assignment through that particular reference. It does not affect whether the type is assignable to another type. After the assignment above, the type of fixed.retries is 3, but the runtime value is 10.
Looking up properties by key
A common reason to write as const on an object is to treat it as a lookup table. The keys become known, so indexing is checked.
const limits = { free: 10, pro: 100, team: 500 } as const;
function limitFor(plan: keyof typeof limits): number {
return limits[plan];
}
limitFor("pro"); // OK
// limitFor("gold");
// error: Argument of type '"gold"' is not assignable to
// parameter of type '"free" | "pro" | "team"'.keyof typeof limits is the union of the key names. If you accept a plain string instead, indexing fails under strict, because the compiler cannot show that an arbitrary string is a key:
const limits = { free: 10, pro: 100, team: 500 } as const;
function unsafeLimit(plan: string) {
// return limits[plan];
// error: Element implicitly has an 'any' type because expression of
// type 'string' can't be used to index type '{ readonly free: 10; ... }'.
return plan in limits ? limits[plan as keyof typeof limits] : undefined;
}When the input comes from outside your program, check it first. A type guard that tests membership is the usual approach, and the next chapters build on it.
The values of the object can be turned into a union too. This is the subject of the chapter on deriving unions, but a preview shows why the exact literals matter:
const limits = { free: 10, pro: 100, team: 500 } as const;
type Limit = (typeof limits)[keyof typeof limits];
// 10 | 100 | 500Without as const, Limit would be number.
What is preserved and what is not
A few more cases come up often when you apply a const assertion to objects.
- Property keys. Keys are always literal names already, so
as constdoes not change them. It only addsreadonly. - Computed keys. A computed key such as
[prefix + "id"]produces an index signature rather than a named property, because the compiler cannot know the key. Use literal keys when you want precise typing. - Functions and methods. A function value keeps its own type. The assertion marks the property that holds it as
readonly, but it does not change the function's parameters or return type. undefinedandnull. These are already literal-like types, so they stay as written.- Non-literal expressions. A const assertion on the object literal is fine even when some property values are not literals, as the
loadexample showed. An assertion directly on a non-literal expression, such asgetName() as const, is an error.
When to use it on objects
as const on an object is a good fit when:
- The object is a constant: settings, route tables, feature flags, lookup maps.
- You need the exact property values in types, for example to pass
options.modeto a function that takes a union. - You want the compiler to reject accidental writes.
It is a poor fit when:
- The object is state that your code updates. Marking it
readonlymakes every update a type error. - The object is built from runtime data. The values are not literals, so the assertion would only add
readonly. - You need a runtime guarantee. A const assertion leaves the emitted JavaScript unchanged.
Exercise
Given const cfg = { env: "prod", port: 443, tags: ["a", "b"] } as const;, write the type of cfg as TypeScript would display it. Then say whether cfg.tags.push("c") and cfg.port = 80 compile.
Show answer
The type is { readonly env: "prod"; readonly port: 443; readonly tags: readonly ["a", "b"] }. Neither statement compiles. cfg.port = 80 fails because port is a read-only property. cfg.tags.push("c") fails because tags is a readonly tuple and has no push method.
Exercise
What is the type of limit in the code below, and why does the let variable not widen to number?
const plans = { free: 10, pro: 100 } as const;
let limit = plans.free;
Show answer
The type of limit is 10. The literal types produced by a const assertion are non-widening, so copying plans.free into a let variable keeps the type 10 instead of widening it to number. To allow other numbers, annotate the variable: let limit: number = plans.free;.
Exercise
In const fixed = { retries: 3 } as const; const loose: { retries: number } = fixed; loose.retries = 10;, which lines does the compiler reject, and what does fixed.retries hold afterwards?
Show answer
The compiler rejects none of them. Readonly properties are assignable to mutable property types, so the assignment to loose is allowed, and writing through loose is allowed too. Afterwards fixed.retries holds 10 at runtime, even though its type is 3.