Sub topic 11
const assertions for literal, readonly data
This chapter assumes you know interface and type alias syntax, union types, readonly properties, and the readonly T[] array type from the earlier chapters. It builds on the point that readonly is shallow and exists only at compile time.
The problem: TypeScript widens literals
When you write an object or array literal, TypeScript picks a type that is useful for later edits. It widens "dark" to string, 3 to number, and an array of strings to string[]. Every property stays mutable.
const widened = { mode: "dark", retries: 3 };
// type: { mode: string; retries: number }
widened.mode = "anything at all"; // allowedThis is usually right for data you plan to change. It is wrong for lookup tables, option lists, and configuration, where you want the exact values to be part of the type. A const assertion, written as const, tells the compiler to keep the narrowest type it can for a literal.
What `as const` does
A const assertion applies three rules to the literal it follows.
- Literal values keep their literal types:
"dark"stays"dark", and3stays3. - Object literal properties become
readonly. - Array literals become
readonlytuples, so the length and the position of each element are fixed.
const fixed = { mode: "dark", retries: 3 } as const;
// type: { readonly mode: "dark"; readonly retries: 3 }
// fixed.mode = "light";
// Error: Cannot assign to 'mode' because it is a read-only property.
const directions = ["up", "down"] as const;
// type: readonly ["up", "down"]
// directions.push("left");
// Error: Property 'push' does not exist on type 'readonly ["up", "down"]'.It is deep, unlike `Readonly<T>`
The earlier chapters showed that Readonly<T> and the readonly modifier are shallow. A const assertion is different, because it reaches every level of the literal you wrote. Nested objects get readonly properties, and nested arrays become readonly tuples.
const settings = {
ui: { theme: "dark", tags: ["a", "b"] },
} as const;
// {
// readonly ui: {
// readonly theme: "dark";
// readonly tags: readonly ["a", "b"];
// };
// }
// settings.ui.theme = "light"; // Error: read-only
// settings.ui.tags.push("c"); // Error: 'push' does not existThis makes as const the cheapest way to get deep immutability for data you write inline. It cannot be applied to a type or to an existing variable. For those cases you need a type such as DeepReadonly<T> from the previous chapter.
Deriving types from values
The most common use of as const is to write a list of values once and derive a union type from it. The value and the type then cannot drift apart.
const roles = ["admin", "editor", "viewer"] as const;
type Role = (typeof roles)[number]; // "admin" | "editor" | "viewer"
function describe(role: Role): string {
return `Role: ${role}`;
}
describe("editor"); // OK
// describe("owner"); // Error: Argument of type '"owner"' is not assignable to parameter of type 'Role'.typeof roles is the readonly tuple type. Indexing it with number gives the union of all element types.
The same technique works for objects. Use keyof typeof to get the keys, and index with those keys to get the values.
const statusLabels = {
active: "Active",
paused: "Paused",
closed: "Closed",
} as const;
type Status = keyof typeof statusLabels; // "active" | "paused" | "closed"
type Label = (typeof statusLabels)[Status]; // "Active" | "Paused" | "Closed"
function label(status: Status): Label {
return statusLabels[status];
}
console.log(label("paused")); // PausedWithout as const, Label would be plain string, and the return type of label would lose its precision.
Common problems
A readonly tuple is not a mutable array
A value declared as const is a readonly tuple. A function that asks for string[] cannot accept it, because the function might call push on it.
const greeting = ["hello", "world"] as const;
function shoutMutable(words: string[]): string {
return words.join(" ").toUpperCase();
}
// shoutMutable(greeting);
// Error: The type 'readonly ["hello", "world"]' is 'readonly'
// and cannot be assigned to the mutable type 'string[]'.
function shout(words: readonly string[]): string {
return words.join(" ").toUpperCase();
}
console.log(shout(greeting)); // HELLO WORLDThe fix is on the function side. If a function does not modify its array argument, declare the parameter readonly string[]. Callers with ordinary arrays can still pass them, because a mutable array is assignable to a readonly one.
`includes` rejects a plain string
includes on a readonly ["admin", "editor", "viewer"] expects one of those three literals. Passing a string is an error, even though that is exactly what a validity check needs to do.
const roles = ["admin", "editor", "viewer"] as const;
type Role = (typeof roles)[number];
function isRole(value: string): value is Role {
// return roles.includes(value); // Error: 'string' is not assignable to '"admin" | "editor" | "viewer"'
return (roles as readonly string[]).includes(value);
}
console.log(isRole("admin")); // true
console.log(isRole("owner")); // falseThe widening cast to readonly string[] is safe, because you are only reading from the array. The value is Role return type is a type predicate, so callers get Role after a successful check.
It only applies to literals
A const assertion works on literal expressions, not on identifiers that hold values.
const base = ["a", "b"];
// const locked = base as const;
// Error: a const assertion can only be applied to literals
// (string, number, boolean, array, object) or enum member references.
const locked = ["a", "b"] as const; // OK: applied at the literalA related trap is a spread. In [...base, "c"] as const, the elements that come from base keep the type string, because base was already widened when it was declared. Only the literal parts you write directly become narrow.
It does nothing at runtime
A const assertion is erased when TypeScript compiles to JavaScript. It does not call Object.freeze. Any code that bypasses the types can still change the data.
const point = { x: 1 } as const;
(point as { x: number }).x = 2; // compiles: readonly does not affect assertions
console.log(point.x); // 2 at runtimeIf you need runtime protection, freeze the object as well.
const frozen = Object.freeze({ x: 1, y: 2 } as const);
// frozen.x = 5; // Error at compile time, and a TypeError at runtime in strict modeObject.freeze is itself shallow. It protects only the top level of the object at runtime. The following table compares the options.
| Tool | Depth | Changes runtime behavior |
|---|---|---|
| `Readonly<T>` | Top level only | No |
| `as const` | Every level of the literal | No |
| `Object.freeze` | Top level only | Yes |
| `DeepReadonly<T>` | Every level of an existing type | No |
Combining `as const` with `satisfies`
A const assertion keeps the exact values but does not check them against a shape. A type annotation checks the shape but throws away the literals. Since TypeScript 4.9, satisfies lets you have both: it validates the literal against a type and leaves the inferred type unchanged.
type Route = { path: string; auth?: boolean };
const routes = {
home: { path: "/" },
admin: { path: "/admin", auth: true },
} as const satisfies Record<string, Route>;
type RouteName = keyof typeof routes; // "home" | "admin"
console.log(routes.admin.auth); // true
// console.log(routes.home.auth);
// Error: Property 'auth' does not exist on type '{ readonly path: "/" }'.Two things in this example connect to earlier chapters.
authis optional inRoute, but the inferred type ofroutes.homehas noauthproperty at all. The compiler tracks what you actually wrote, not what the shape allows. An annotationconst routes: Record<string, Route>would instead let you readroutes.home.authasboolean | undefined.- The readonly object is accepted where
Routeis expected, becausereadonlydoes not affect assignability.
If you are on a TypeScript version older than 4.9, write the annotation on a separate helper or check the shape with a function parameter instead.
When to use it
Use as const when the data is a fixed table, a list of allowed values, or a configuration object whose literal values matter to other types. Avoid it for data that you build up or edit over time, such as a list of items the user adds to. For that data a readonly tuple would only force casts.
Prefer deriving types from as const values over writing a union and a list separately. A string-literal union plus an array that repeats the same strings can fall out of sync. A single as const array cannot.
Exercises
Exercise
Given const sizes = ["s", "m", "l"] as const;, write the type alias Size that is the union "s" | "m" | "l", and explain why sizes.includes(input) fails to compile when input is a string.
Show answer
type Size = (typeof sizes)[number];. The includes method on readonly ["s", "m", "l"] accepts only "s" | "m" | "l", so a string argument is rejected. Cast the array to readonly string[] before calling includes, for example (sizes as readonly string[]).includes(input).
Exercise
What are the types of a.list and b.list below, and which assignments to them compile?
const a = { list: ["x"] };
const b = { list: ["x"] } as const;
a.list.push("y");
b.list.push("y");
Show answer
a.list is string[], so a.list.push("y") compiles. b.list is readonly ["x"], so b.list.push("y") is an error because push does not exist on a readonly tuple. The const assertion applies to the nested array as well as the outer object.