Sub topic 4
Keeping literal types with as const
This chapter assumes you know basic TypeScript types, how to annotate functions, and how object literals and switch work in JavaScript. It also assumes you have read the previous chapter, which explained why let widens a literal to string while const keeps "up". Here you will learn how to keep literal types inside objects and arrays, where const alone cannot help.
The problem: const protects the binding, not the contents
const stops you from reassigning a variable. It does not stop you from changing the properties of an object stored in that variable. TypeScript follows the same rule when it infers types. For an object literal it assumes you may change each property later, so it widens each property to its base type.
type Direction = "up" | "down" | "left" | "right";
function move(direction: Direction): void {
console.log(`Moving ${direction}`);
}
const options = { direction: "up", speed: 3 };
// inferred: { direction: string; speed: number }
move(options.direction);
// Error: Argument of type 'string' is not assignable to parameter of type 'Direction'.The value is clearly "up", but the property type is string, so the call fails. A const assertion fixes this.
What as const does
Add as const after an expression, and TypeScript infers the narrowest type it can for that expression. A const assertion applies three rules:
- String, number, and boolean literals keep their literal types (
"up",3,true) instead of widening. - Every property in an object literal becomes
readonly. - Every array literal becomes a
readonlytuple with a fixed length and known element types.
The rules apply recursively, so nested objects and arrays are affected too.
const options = { direction: "up", speed: 3 } as const;
// inferred: { readonly direction: "up"; readonly speed: 3 }
move(options.direction); // OK: the property type is "up"
options.speed = 4;
// Error: Cannot assign to 'speed' because it is a read-only property.The assertion is not a cast that changes the value. It changes only how the compiler reads the literal you wrote. No code appears in the compiled JavaScript.
Correction: the diagram must use the required fence format, so it follows below.
Arrays and tuples
Without as const, an array literal gets an array type with a widened element type. With it, you get a readonly tuple.
const loose = ["small", "medium", "large"];
// string[]
const fixed = ["small", "medium", "large"] as const;
// readonly ["small", "medium", "large"]
console.log(fixed[0]); // "small", and its type is "small"
console.log(fixed.length); // type 3Tuple types track position, so fixed[1] has type "medium". Methods that mutate the array, such as push and pop, do not exist on a readonly tuple, and the compiler reports an error if you call them.
fixed.push("huge");
// Error: Property 'push' does not exist on type 'readonly ["small", "medium", "large"]'.Turning an array into a union
An indexed access with number gives the union of all element types. Combined with typeof, this derives a union from a runtime array.
const sizes = ["small", "medium", "large"] as const;
type Size = (typeof sizes)[number]; // "small" | "medium" | "large"
function order(size: Size): string {
return `Ordered a ${size} coffee`;
}
order("medium"); // OK
order("huge"); // Error: Argument of type '"huge"' is not assignable to parameter of type 'Size'.This pattern keeps one source of truth. You can loop over sizes at runtime to build a menu, and the type Size updates when you edit the array. If you wrote the union and the array separately, they could drift apart.
Objects: deriving a union from values
The same idea works for objects. Use keyof typeof to get the keys, and index with those keys to get the values.
const Status = {
Active: "active",
Inactive: "inactive",
} as const;
type StatusKey = keyof typeof Status; // "Active" | "Inactive"
type StatusValue = (typeof Status)[StatusKey]; // "active" | "inactive"
function label(status: StatusValue): string {
return status === Status.Active ? "On" : "Off";
}
label(Status.Active); // OK
label("inactive"); // OKHere typeof Status takes the type of the value, and keyof takes the union of its property names. Indexing a type by a key union gives the union of the matching property types. You can give the type the same name as the constant, because types and values live in separate namespaces. This is a common way to get enum-like access from a plain object. The later chapter on choosing between enums and unions compares this with real enums.
Where as const is allowed
A const assertion works only on literal expressions: string, number, boolean, array, and object literals, and references to enum members. It cannot be applied to a general expression.
function getName(): string {
return "Ada";
}
const name = getName() as const;
// Error: A 'const' assertion can only be applied to references to enum members,
// or string, number, bigint, boolean, array, or object literals.This restriction makes sense. The compiler cannot know what a function call returns at compile time beyond its declared type, so there is no narrower literal type to keep.
You can also use as const on a single value, including with let:
let direction = "up" as const; // type: "up"
direction = "down";
// Error: Type '"down"' is not assignable to type '"up"'.This is rarely useful, because a let that can only ever hold "up" is almost always a mistake. If you want a variable that holds one of several values, annotate it with the union: let direction: Direction = "up";.
The readonly trap with function parameters
Readonly tuples are not assignable to mutable array types. This surprises many people when they pass an as const array to an existing function.
function sum(values: number[]): number {
return values.reduce((total, n) => total + n, 0);
}
const nums = [1, 2, 3] as const;
sum(nums);
// Error: The type 'readonly [1, 2, 3]' is 'readonly' and cannot be assigned
// to the parameter of type 'number[]'.TypeScript refuses because sum could, in principle, mutate the array and break the readonly promise. If sum does not mutate, declare its parameter as readonly number[]. A mutable array is assignable to a readonly one, so this accepts both kinds.
function sumReadonly(values: readonly number[]): number {
return values.reduce((total, n) => total + n, 0);
}
sumReadonly(nums); // OK
sumReadonly([4, 5, 6]); // OKMaking parameters readonly wherever the function does not mutate them is good practice anyway. It documents intent and avoids this error. If you cannot change the function (for example, it comes from a library), copy the array first: sum([...nums]).
Compile-time only: as const does not freeze anything
The readonly modifier exists only in the type system. At runtime the compiled JavaScript has no trace of it, and the object remains mutable. Code that bypasses the type checker can still change it.
const Settings = { theme: "dark" } as const;
// The compiler blocks this assignment:
// Settings.theme = "light";
// A cast removes the protection, and the change succeeds at runtime:
(Settings as { theme: string }).theme = "light";
console.log(Settings.theme); // "light"If you need runtime protection, for example when you pass the object to code you do not control, add Object.freeze. In strict mode, writing to a frozen object throws a TypeError. Note that Object.freeze is shallow, so nested objects need their own freeze.
const Frozen = Object.freeze({ theme: "dark" } as const);Treat as const as a tool for inference, and Object.freeze as a tool for runtime safety. They solve different problems and can be used together.
Choosing between const, as const, annotations, and satisfies
Several tools control how a value is typed. This table summarizes when each one fits.
| Tool | What it does | Use it when |
|---|---|---|
| `const x = "up"` | Keeps the literal type for a primitive binding | You declare a single primitive that never changes |
| `x = { ... } as const` | Keeps literals, adds `readonly`, makes tuples | You want exact literal types for a whole object or array |
| `const x: T = ...` | Forces the type to `T` and discards narrower inference | You want the variable typed as a declared contract |
| `x = { ... } satisfies T` | Checks the value against `T` and keeps the inferred type | You want validation without losing literal detail |
The last two rows are often confused. An annotation replaces the inferred type, so details disappear. satisfies only checks, so the inferred type survives. You can combine as const and satisfies when you want both exact literals and a shape check, and a later chapter covers this in detail.
type Route = { path: string; method: "GET" | "POST" };
const routes = {
home: { path: "/", method: "GET" },
submit: { path: "/submit", method: "POST" },
} as const satisfies Record<string, Route>;
type RouteName = keyof typeof routes; // "home" | "submit"The check catches typos such as method: "PUT". The as const keeps routes.home.path typed as "/". Without as const, satisfies would still check the shape, but the properties would infer as the widened "GET" | "POST" union only through contextual typing, and the exact paths would be lost.
Common errors and how to read them
- "Argument of type 'string' is not assignable to parameter of type ..." after passing an object property. The object was inferred with widened properties. Add
as constto the object, or annotate it with a type that uses the union. - "Cannot assign to '...' because it is a read-only property." You added
as constand then tried to mutate. Either the mutation is a bug, or the object should not useas const. Use a typed annotation if you need a mutable object with literal-typed fields. - "The type 'readonly [...]' is 'readonly' and cannot be assigned to the parameter of type '...[]'." A function expects a mutable array. Change its parameter to
readonly T[], or pass a copy. - "A 'const' assertion can only be applied to ..." You used
as conston a non-literal expression such as a function call or a variable. Put the literal directly in the expression.
Summary of behavior to remember
as constkeeps literal types, addsreadonlyto object properties, and turns arrays into readonly tuples, all recursively.- It affects only types. The emitted JavaScript is unchanged and the object stays mutable at runtime.
(typeof arr)[number]derives a union from an array, and(typeof obj)[keyof typeof obj]derives one from an object's values.- Readonly tuples need
readonlyparameter types in the functions that receive them.
Exercise
Given const levels = ["debug", "info", "warn"] as const;, write a type Level derived from it. Then explain why function logAll(items: string[]) {} rejects logAll(levels), and give two ways to fix the call.
Show answer
type Level = (typeof levels)[number]; gives "debug" | "info" | "warn". The call is rejected because levels has the type readonly ["debug", "info", "warn"], and a readonly tuple is not assignable to the mutable string[] parameter, since the function might mutate it. Fix 1: change the parameter to readonly string[], which accepts both mutable and readonly arrays. Fix 2: pass a copy, such as logAll([...levels]), which creates a mutable ("debug" | "info" | "warn")[].
Exercise
A teammate writes const mode = getMode() as const; to keep a narrow type for the result of getMode(). Why does this fail, and what should they do instead?
Show answer
A const assertion can only be applied to literal expressions (string, number, boolean, array, or object literals) and enum member references, not to function calls. The compiler has no literal value to preserve. They should annotate the function's return type with the union, for example function getMode(): "dark" | "light", or annotate the variable: const mode: "dark" | "light" = getMode();.