Sub topic 11
Const Assertions for Literal, Readonly Data
Assume you know basic TypeScript annotations, interfaces, unions, and JavaScript objects and arrays. This chapter focuses on as const, which preserves literal values and adds readonly types to literal data.
Why ordinary inference can be too broad
TypeScript often widens values to general types. A property initialized with "dark" may become string, because the property could later be changed:
const settings = {
theme: "dark",
};
settings.theme = "light"; // allowedThe type of settings.theme is string, not the literal type "dark". Literal types describe one exact value, such as "dark", 42, or true.
A const variable prevents reassignment of the variable itself. It does not make an object immutable:
const user = { name: "Ada" };
user.name = "Grace"; // allowed
// user = { name: "Grace" }; // Error: cannot assign to a const variableThe as const assertion requests the narrowest literal interpretation of a literal expression.
What `as const` changes
For an object literal, as const:
- Preserves literal property types.
- Adds
readonlyto the properties. - Applies these effects through nested literal expressions.
For an array literal, it creates a readonly tuple. A tuple is an array type with a fixed number of elements and a known type at each position.
const request = {
method: "GET",
cache: true,
} as const;
// typeof request is:
// {
// readonly method: "GET";
// readonly cache: true;
// }
// request.method = "POST"; // Error: read-only propertyThe value of request.method is now exactly "GET". This helps when an API accepts only specific string values.
function sendRequest(method: "GET" | "POST"): void {
console.log(`Sending ${method}`);
}
sendRequest(request.method); // OK
// sendRequest("DELETE"); // ErrorThis is useful for configuration objects, action descriptions, protocol messages, and other data whose values form a fixed set.
Arrays become readonly tuples
Without as const, an array usually becomes a mutable array with a broad element type:
const normal = ["up", "down"]; // string[]With as const, TypeScript preserves both the values and their positions:
const directions = ["up", "down"] as const;
// readonly ["up", "down"]
type Direction = (typeof directions)[number];
// "up" | "down"
function move(direction: Direction): void {
console.log(`Moving ${direction}`);
}
move("up"); // OK
// move("left"); // ErrorThe expression (typeof directions)[number] means “the type of any numeric element in this tuple.” It produces the union of its element types.
You cannot mutate a readonly tuple:
// directions.push("left"); // Error
// directions[0] = "left"; // ErrorA readonly tuple can still be passed to a function that reads an array:
function printDirections(values: readonly string[]): void {
for (const value of values) {
console.log(value);
}
}
printDirections(directions); // OKCompare the related tools
| Feature | Prevents variable reassignment | Narrows literals | Prevents property mutation |
|---|---|---|---|
| `const` declaration | Yes | Sometimes | No |
| `readonly` property | No | No | Yes, statically |
| `as const` assertion | No | Yes | Yes, statically |
A const assertion changes TypeScript’s inferred type. It does not freeze the JavaScript value at runtime.
Common gotchas
as const applies to a literal expression, not to every value reachable from it. A separately created mutable object can remain mutable through a readonly property:
const shared = { enabled: true };
const config = { shared } as const;
config.shared.enabled = false; // allowed
// config.shared = { enabled: true }; // ErrorThe shared property cannot be replaced, but the object referenced by that property still has a mutable type.
Also, as const is different from a type annotation. An annotation checks that a value fits a type. A const assertion changes how TypeScript infers the value’s type. Use it when the literal value itself should define a precise union or readonly structure.
Exercise
What are the inferred type and mutation behavior of const colors = ["red", "blue"] as const?
Show answer
Its type is readonly ["red", "blue"]. The element values remain the literals "red" and "blue", and operations such as colors.push("green") or colors[0] = "green" are rejected by TypeScript.