Sub topic 6
Preserving literals with as const
Earlier chapters covered keyof, typeof, and indexed access types. Those operators can only read the types that already exist. This chapter covers as const, which controls how precise those types are. It assumes you know interfaces, type aliases, union types, and basic generics. It also assumes you can read keyof typeof obj and T[K] from the earlier chapters.
By the end, you will be able to explain why TypeScript widens literal values, say what as const changes, and turn one runtime object or array into both values and types. You will also be able to fix the errors that readonly produces.
Why literals get widened
A literal type is a type with exactly one possible value, such as "admin" or 3. TypeScript often replaces a literal type with its general type, such as string or number. This is called widening. It happens when TypeScript decides that the value might change later.
const a = "admin"; // type: "admin"
let b = "admin"; // type: string
const settings = { mode: "dark", retries: 3 };
// type: { mode: string; retries: number }
const list = ["admin", "editor"];
// type: string[]The first two lines show the basic rule. A const variable cannot be reassigned, so its type stays "admin". A let variable can be reassigned, so its type widens to string.
The object case is less obvious. settings is a const, but its properties are mutable. You can write settings.mode = "light", so TypeScript types mode as string. Array elements widen for the same reason.
Widening is usually what you want. It becomes a problem when you try to derive types from the value:
const settings = { mode: "dark", retries: 3 };
type Mode = (typeof settings)["mode"]; // string, not "dark" | "light"The derived type is only as precise as the value's type. If the value's type has been widened, everything derived from it is vague too.
What as const does
as const is a const assertion. You put it after a literal expression, and it tells the compiler to use the narrowest type for that expression. It has three effects:
| Literal expression | Without `as const` | With `as const` |
|---|---|---|
| `"dark"` in a `let` | `string` | `"dark"` |
| `{ mode: "dark", retries: 3 }` | `{ mode: string; retries: number }` | `{ readonly mode: "dark"; readonly retries: 3 }` |
| `["a", "b"]` | `string[]` | `readonly ["a", "b"]` |
Each effect in detail:
- Strings, numbers, and booleans keep their literal types instead of widening.
- Object properties become
readonly. - Array literals become
readonlytuples. A tuple is an array type with a fixed length and a known type at each position.
The assertion applies to nested literals as well:
const frozen = {
mode: "dark",
retries: 3,
tags: ["ui", "beta"],
limits: { min: 1, max: 5 },
} as const;
type Frozen = typeof frozen;
// {
// readonly mode: "dark";
// readonly retries: 3;
// readonly tags: readonly ["ui", "beta"];
// readonly limits: { readonly min: 1; readonly max: 5 };
// }
// frozen.retries = 4;
// Error: Cannot assign to 'retries' because it is a read-only property.The diagram below summarizes the choice.
as const is a compile-time feature only
as const changes the type, not the runtime value. The emitted JavaScript contains no assertion, and the object is not frozen. If you want a runtime guarantee, you need Object.freeze as well. The readonly modifier only stops TypeScript code from writing to the property. Code that bypasses the type system, such as a cast to any, can still mutate it.
Using as const in other positions
You can apply as const to a single value as well as to a whole object:
let mode = "dark" as const; // type: "dark"
// mode = "light"; // Error: Type '"light"' is not assignable to type '"dark"'.This is rarely useful on its own. It is more useful when a function returns a tuple. Without the assertion, a returned array literal is typed as an array of a union:
function loose() {
return ["ok", 200];
}
// return type: (string | number)[]
function precise() {
return ["ok", 200] as const;
}
// return type: readonly ["ok", 200]
const [label, code] = precise(); // label: "ok", code: 200The tuple form lets destructuring give each variable its own type. React hooks and similar APIs rely on this pattern.
Deriving a union from an as const object
The most common use of as const is to define a set of allowed values once and derive a type from it. Here is the approach with an object. It uses keyof typeof from the earlier chapter and an indexed access type.
const STATUS = {
Idle: "idle",
Loading: "loading",
Done: "done",
} as const;
type StatusKey = keyof typeof STATUS; // "Idle" | "Loading" | "Done"
type Status = (typeof STATUS)[keyof typeof STATUS]; // "idle" | "loading" | "done"
function describe(status: Status): string {
switch (status) {
case STATUS.Idle:
return "Waiting";
case STATUS.Loading:
return "Working";
case STATUS.Done:
return "Finished";
}
}
console.log(describe(STATUS.Loading)); // WorkingRead (typeof STATUS)[keyof typeof STATUS] from the inside out:
typeof STATUSis the object's type, with literal values andreadonlyproperties.keyof typeof STATUSis the union of its keys.- Indexing the object type with that union gives the union of all the property types.
Without as const, step 3 would produce string, and describe would accept any string. With it, the compiler checks that the switch handles every member. If you add Failed: "failed" to STATUS, Status grows automatically, and describe then fails to compile because it no longer returns a value on every path. That is useful, because it points you to every place that needs updating.
This pattern is a common alternative to a TypeScript enum. An as const object produces no extra runtime construct, and its values are plain strings that work well with JSON and with other code.
Deriving a union from an as const array
When you only need a list of values and not named keys, use an array. The spine example for this chapter does exactly that:
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number]; // "admin" | "editor" | "viewer"
function isRole(value: string): value is Role {
return (ROLES as readonly string[]).includes(value);
}
console.log(isRole("admin")); // true
console.log(isRole("owner")); // false(typeof ROLES)[number] indexes the tuple type with number, which gives the union of every element type. The next chapter covers this lookup in detail. For now, remember the shape: as const makes the elements literal, and indexing with number collects them.
The array is the single source of truth. The runtime code can loop over ROLES to build a dropdown or validate input, and the type Role updates whenever the array changes. This avoids writing the same list twice, which is a common way for a type and its runtime check to drift apart.
isRole is a type guard. Its return type value is Role tells the compiler that, inside an if (isRole(x)) block, x has the type Role. The cast ROLES as readonly string[] is needed because includes on a tuple of literals only accepts those literals as its argument. Passing a plain string would be a compile error. The cast widens the array's type for that one call.
Common errors and how to fix them
Most problems with as const come from the readonly modifier it adds.
Readonly arrays are not assignable to mutable ones
A readonly array cannot be passed where a mutable array is expected. The mutable type allows methods such as push, and passing the readonly array would let those methods modify it.
const ROLES = ["admin", "editor", "viewer"] as const;
function printAll(items: string[]): void {
items.forEach((item) => console.log(item));
}
// printAll(ROLES);
// Error: The type 'readonly ["admin", "editor", "viewer"]' is 'readonly'
// and cannot be assigned to the mutable type 'string[]'.
function printAllReadonly(items: readonly string[]): void {
items.forEach((item) => console.log(item));
}
printAllReadonly(ROLES); // OKThe correct fix is to change the function parameter to readonly string[], as shown. A function that only reads its input should declare that. Copying the array with [...ROLES] also works, but it hides the real issue.
as const only works on literal expressions
TypeScript only accepts the assertion on literals, enum members, and references to them. It rejects it on arbitrary expressions:
const raw = ["a", "b"];
// const frozen = raw as const;
// Error: A 'const' assertions can only be applied to references to enum members,
// or string, number, boolean, array, or object literals.raw was already typed as string[] when it was declared, and as const cannot recover the lost literals. Put the assertion on the literal where you first write it.
Nested variables keep their own types
The assertion only affects what is written inside the literal. If you place a variable inside it, the variable keeps whatever type it already had:
const inner = { min: 1, max: 5 }; // { min: number; max: number }
const outer = { limits: inner, label: "box" } as const;
// { readonly limits: { min: number; max: number }; readonly label: "box" }The limits property is readonly, but inner's own properties are still mutable numbers. Apply as const to inner as well, or write the nested object inline.
Literal types reject runtime strings
Once values are literal types, ordinary strings no longer fit. Data from user input, JSON, or Object.keys is typed as string. You must narrow it first, for example with a type guard like isRole above. This is the intended behavior, because the compiler cannot know that an arbitrary string belongs to the set.
Combining as const with satisfies
as const gives the narrowest type but does not check that the value has the right shape. The satisfies operator, available since TypeScript 4.9, adds that check without widening the type back:
const ROUTES = {
home: "/",
profile: "/profile",
} as const satisfies Record<string, string>;
type Route = (typeof ROUTES)[keyof typeof ROUTES]; // "/" | "/profile"If someone adds a route whose value is a number, the satisfies check reports an error at the definition. The derived Route type still keeps the exact string literals.
When to choose as const
Use as const when a single value should drive both runtime behavior and a type: option lists, status codes, route tables, configuration keys, and event names. Avoid it for data that is meant to change at runtime, such as a list you push items into. A readonly type on such data causes errors with no benefit.
Exercise
What are the types of a and b below, and why?
const a = ["x", "y"] as const;
const b = ["x", "y"];
Show answer
a is readonly ["x", "y"], a readonly tuple of two literal types. b is string[], because without as const the array's elements are mutable and so the literals widen to string. Only a supports (typeof a)[number] giving "x" | "y". For b the same lookup gives string.
Exercise
Given the object below, write a type Level equal to 1 | 2 | 3, derived from the object. Then say what would change if as const were removed.
const LEVELS = { low: 1, mid: 2, high: 3 } as const;
Show answer
type Level = (typeof LEVELS)[keyof typeof LEVELS]; gives 1 | 2 | 3. Without as const, the property types widen to number, so Level would be just number and would accept any number.