Sub topic 2
What `as const` does
This chapter assumes you know basic TypeScript types, the difference between let and const, union types, and typeof in type positions.
A const assertion uses as const to tell TypeScript to keep the narrowest possible type for a literal expression. It also makes properties and array elements readonly in the resulting type.
const direction = "left" as const;
// type: "left"
const point = { x: 10, y: 20 } as const;
// type: { readonly x: 10; readonly y: 20 }
const pair = ["id", 1] as const;
// type: readonly ["id", 1]The assertion changes how TypeScript checks the code. It does not change the JavaScript value at runtime.
Why TypeScript widens literals
A literal is a value written directly in code, such as "left", 10, or true. TypeScript can represent the exact value as a literal type:
"left"is a string literal type.10is a numeric literal type.trueis a boolean literal type.
However, TypeScript often widens a literal. Widening replaces a specific literal type with a broader type such as string or number.
let a = "left";
// string
const b = "left";
// "left"
const config = { mode: "dark", retries: 3 };
// { mode: string; retries: number }The let variable can later hold another string, so string is appropriate. A const variable cannot be reassigned, so TypeScript can preserve "left".
An object is different. The variable cannot be reassigned, but its properties can usually be changed:
const config = { mode: "dark", retries: 3 };
config.mode = "light"; // allowed
config.retries = 4; // allowedBecause config.mode is mutable, TypeScript widens its type to string. The same reasoning widens retries to number.
The three effects of `as const`
When applied to a literal expression, as const has three related effects:
- It prevents literal widening.
- It marks object properties as
readonly. - It turns array literals into readonly tuples.
const settings = {
mode: "dark",
retries: 3,
} as const;
// {
// readonly mode: "dark";
// readonly retries: 3;
// }Now these assignments fail during type checking:
// settings.mode = "light";
// Error: Cannot assign to 'mode' because it is a read-only property.
// settings.retries = 4;
// Error: Cannot assign to 'retries' because it is a read-only property.The property types are exact. settings.mode has type "dark", not string, and settings.retries has type 3, not number.
The readonly behavior applies recursively to literal parts of the expression:
const app = {
name: "portal",
features: {
auditLog: true,
},
} as const;
// app.features.auditLog has type true
// app.features.auditLog is readonlyThe important point is that this is a type-level description. It does not freeze the object at runtime.
Arrays become readonly tuples
Without as const, TypeScript normally infers an array with a common element type:
const values = ["id", 1];
// (string | number)[]The array can have more elements, and its elements can be replaced. TypeScript therefore does not preserve the position or exact value of each element.
With as const, TypeScript infers a tuple. A tuple is an array type with a fixed number of positions, where each position can have its own type.
const pair = ["id", 1] as const;
// readonly ["id", 1]
const first = pair[0];
// "id"
const second = pair[1];
// 1The tuple has two positions. The first position must contain "id", and the second must contain 1.
Mutation methods are unavailable because the tuple is readonly:
// pair.push(2);
// Error: Property 'push' does not exist on type 'readonly ["id", 1]'.
// pair[0] = "name";
// Error: Cannot assign to '0' because it is a read-only property.This distinction is useful when a value describes fixed data, such as a coordinate, a command and its argument, or a list of supported names.
`const` is different from `as const`
The const keyword controls reassignment of a variable:
const name = "Ada";
// name = "Grace"; // errorThe as const assertion controls the inferred type of a literal expression:
let name = "Ada" as const;
// name = "Grace"; // error because name has type "Ada"Here, let still creates a reassignable variable in JavaScript, but TypeScript rejects any new value that is not exactly "Ada". The keyword and the assertion solve different problems.
Use const when a variable binding should not be reassigned. Use as const when the exact literal types and readonly structure matter.
When to use it
Use as const for values that act as fixed definitions:
- configuration values whose fields should not change
- command names and their fixed arguments
- lookup objects with exact string values
- arrays that define a fixed set or fixed sequence
- runtime data from which you want to derive narrow TypeScript types
Do not add it automatically to every value. A readonly type can make a value incompatible with a function that expects a mutable array or object. Apply it when immutability and exact literal types express the intended design.
const command = ["open", "/tmp/report.txt"] as const;
function runCommand(input: readonly [string, string]): string {
return `${input[0]} ${input[1]}`;
}
console.log(runCommand(command));
// open /tmp/report.txtExercise
What is the inferred type of const result = { ok: true, count: 0 } as const, and which assignments are rejected: result.ok = false or result.count = 1?
Show answer
The type is { readonly ok: true; readonly count: 0 }. Both assignments are rejected because the properties are readonly and retain their exact literal types.