Sub topic 6
Preserving literals with `as const`
Prerequisites
This chapter assumes you know basic TypeScript types, union types, JavaScript arrays and objects, and the basics of generics. It also assumes you have seen keyof and indexed access types such as T[K].
TypeScript often widens values to general types. For example, a string variable usually gets the type string, not the exact string value "admin":
let role = "admin";
// type: string
const fixedRole = "admin";
// type: "admin"A const variable keeps a literal type when TypeScript can guarantee that the variable itself will not be reassigned. However, arrays and objects are still usually widened:
const roles = ["admin", "editor", "viewer"];
// type: string[]
const settings = {
mode: "dark",
compact: true,
};
// type: { mode: string; compact: boolean }The array is treated as a mutable list of strings. The object properties are treated as mutable values. TypeScript does not assume that roles will always contain only those three strings.
What `as const` changes
as const is a const assertion. It tells TypeScript to preserve literal values instead of widening them.
const ROLES = ["admin", "editor", "viewer"] as const;
// type: readonly ["admin", "editor", "viewer"]
const SETTINGS = {
mode: "dark",
compact: true,
} as const;
// type: {
// readonly mode: "dark";
// readonly compact: true;
// }For an array, as const creates a readonly tuple. A tuple is an array type with a known number of elements and a known type at each position. For an object, it makes properties readonly and preserves their literal value types.
| Expression | Inferred type |
|---|---|
| `["admin", "editor"]` | `string[]` |
| `["admin", "editor"] as const` | `readonly ["admin", "editor"]` |
| `{ mode: "dark" }` | `{ mode: string }` |
| `{ mode: "dark" } as const` | `{ readonly mode: "dark" }` |
Readonly means the value cannot be changed through that type:
const ROLES = ["admin", "editor", "viewer"] as const;
// ROLES.push("owner"); // Error
// ROLES[0] = "owner"; // ErrorThis restriction is useful when the value is intended to be a fixed source of truth.
Deriving a union from an array
The type of a readonly tuple can be indexed with number. This means “the type of any numeric element”:
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];
// "admin" | "editor" | "viewer"
function greet(role: Role): string {
return `Welcome, ${role}`;
}
console.log(greet("admin"));
console.log(greet("viewer"));
// greet("owner"); // ErrorThe expression typeof ROLES gets the type of the runtime variable. The [number] indexed access then collects the types of all tuple elements. The result is a union of string literal types.
This pattern keeps runtime data and compile-time types together:
const STATUSES = ["pending", "approved", "rejected"] as const;
type Status = (typeof STATUSES)[number];
function isStatus(value: string): value is Status {
return (STATUSES as readonly string[]).includes(value);
}
const input = "approved";
if (isStatus(input)) {
const status: Status = input;
console.log(status);
}Without as const, (typeof STATUSES)[number] would be just string, so any string would be accepted as a Status.
Fixed objects and their keys
The same technique works for objects. Use keyof typeof to derive the keys and indexed access to derive the values:
const HTTP_STATUS = {
ok: 200,
notFound: 404,
serverError: 500,
} as const;
type StatusName = keyof typeof HTTP_STATUS;
// "ok" | "notFound" | "serverError"
type StatusCode = (typeof HTTP_STATUS)[StatusName];
// 200 | 404 | 500A diagram of the type derivation:
Use as const when a value represents a fixed vocabulary, configuration table, event list, or other data whose exact literals matter. Do not use it automatically for mutable application state, because readonly types can make later updates invalid.
Exercise
What is the type of type Flavor = (typeof FLAVORS)[number] when const FLAVORS = ["vanilla", "chocolate"] as const?
Show answer
Flavor is "vanilla" | "chocolate". The tuple's numeric indexed access collects the literal type of each element.