Sub topic 15
Preserving literals with as const
This chapter assumes you already know how const and let infer different types, how arrays and tuples are typed, what readonly does on a property, and how literal unions work. Here you will learn how a const assertion (as const) stops TypeScript from widening the literals in an expression. You will also see how to derive types from data you have already written.
The problem: widening inside objects and arrays
A const variable holding a string literal keeps the literal type. Properties of an object and elements of an array are different, because they can be reassigned later. TypeScript widens them to their primitive types.
const direction = "up"; // type "up"
const settings = { mode: "dev", retries: 3 }; // { mode: string; retries: number }
const ports = [80, 443]; // number[]The widening causes errors when a function expects a literal union:
type Mode = "dev" | "prod";
function start(mode: Mode): void {
console.log(`starting in ${mode}`);
}
const settings = { mode: "dev" };
// start(settings.mode);
// Error: Argument of type 'string' is not assignable to parameter of type 'Mode'.You could annotate settings with a type that names Mode. A const assertion fixes it without restating the shape.
What as const does
Putting as const after an object, array, or primitive literal changes how TypeScript reads that expression. It has three effects:
- Literal types are not widened.
"dev"stays"dev"and3stays3. - Object properties become
readonly. - Array literals become
readonlytuples with a known length and known element types.
const config = { mode: "dev", ports: [80, 443] } as const;
// {
// readonly mode: "dev";
// readonly ports: readonly [80, 443];
// }
type Mode = "dev" | "prod";
function start(mode: Mode): void {
console.log(`starting in ${mode}`);
}
start(config.mode); // ok: config.mode has the type "dev"The assertion applies to every nested literal, not just the top level. That is why ports became a readonly [80, 443] tuple instead of number[].
Arrays and tuples
Without an annotation, an array literal infers a plain array type. as const turns it into a tuple:
const loose = [1, "a"]; // (string | number)[]
const fixed = [1, "a"] as const; // readonly [1, "a"]This is useful for functions that return several values. Without the assertion, the return type is an array of a union, and destructuring loses the position information.
function minMax(values: number[]) {
return [Math.min(...values), Math.max(...values)] as const;
}
const [lo, hi] = minMax([3, 1, 2]); // both are number
console.log(lo, hi); // 1 3The return type is readonly [number, number]. The elements are number rather than literals because Math.min returns number. as const only preserves literals that appear in the expression itself.
Deriving types from values
The most common use of as const is to keep one source of truth. You write the data once, then derive the type from it with typeof and an indexed access type.
const LEVELS = ["debug", "info", "warn", "error"] as const;
type Level = (typeof LEVELS)[number];
// "debug" | "info" | "warn" | "error"
function log(level: Level, message: string): void {
console.log(`[${level}] ${message}`);
}
log("info", "started");
// log("verbose", "started"); // Error: not assignable to type 'Level'(typeof LEVELS)[number] means "the type of any element of this tuple". Adding "trace" to the array updates Level automatically.
The same pattern works for object keys and values:
const STATUS = { ok: 200, notFound: 404 } as const;
type StatusName = keyof typeof STATUS; // "ok" | "notFound"
type StatusCode = (typeof STATUS)[StatusName]; // 200 | 404Checking untrusted input against the list
A runtime string from user input is not a Level, so calling LEVELS.includes(input) directly is a type error. The tuple's includes method only accepts Level arguments. Widen the list for the check and report the result with a type predicate:
const LEVELS = ["debug", "info", "warn", "error"] as const;
type Level = (typeof LEVELS)[number];
function isLevel(value: string): value is Level {
return (LEVELS as readonly string[]).includes(value);
}
const input: string = "warn";
if (isLevel(input)) {
console.log(input); // input is narrowed to Level here
}The as readonly string[] is a type assertion, and it is safe here because every Level is a string. You are widening, not claiming something the compiler cannot verify.
Combining as const with satisfies
as const does not check the shape of your data. A typo in a property name passes silently. Adding satisfies validates the object while keeping the precise literal types:
type Route = {
path: string;
methods: readonly ("GET" | "POST")[];
};
const routes = {
home: { path: "/", methods: ["GET"] },
submit: { path: "/submit", methods: ["GET", "POST"] },
} as const satisfies Record<string, Route>;
type RouteName = keyof typeof routes; // "home" | "submit"Note that Route uses readonly for methods. Because as const makes the arrays readonly tuples, a satisfies target with a mutable ("GET" | "POST")[] would fail. The as const satisfies T order requires TypeScript 5.0 or later. On older versions, write satisfies T and add as const to the inner literals instead.
Gotchas
readonly is a compile-time rule
as const produces no runtime code. The object is not frozen, and code that bypasses the type system can still mutate it. Use Object.freeze when you need runtime protection, and remember it is shallow.
Readonly arrays do not fit mutable parameters
A readonly array cannot be passed where a mutable array is expected, because the function could mutate it.
const nums = [1, 2, 3] as const;
function sum(values: readonly number[]): number {
return values.reduce((total, n) => total + n, 0);
}
console.log(sum(nums)); // 6If sum took number[], the call would fail with "The type 'readonly [1, 2, 3]' is 'readonly' and cannot be assigned to the mutable type 'number[]'". Declare parameters that only read an array as readonly T[]. This also makes the function accept both kinds of array.
It only works on literals
A const assertion must be applied to a literal expression: a string, number, boolean, array, object, or enum member. These forms are errors:
declare function getName(): string;
const name = "Ada";
// const a = getName() as const; // Error: only literals are allowed
// const b = name as const; // Error: a variable reference is not a literal
const c = "Ada" as const; // ok: type "Ada"Mutating the result
Methods like push do not exist on a readonly tuple. If you need a mutable copy, spread it into a new array: const copy = [...LEVELS]. The copy has type ("debug" | "info" | "warn" | "error")[].
Choosing between the alternatives
| Approach | Keeps literals | Runtime value | Typical use |
|---|---|---|---|
| Type annotation with a union | Yes, as written | None | A parameter or field type |
| `as const` object or array | Yes, inferred | Yes, a plain object or array | One list used for both values and types |
| `enum` | Yes | Yes, generated code | Code that needs reverse mapping or an existing enum API |
| `satisfies` alone | Partly, depends on context | Yes | Validating a shape while keeping inferred types |
For most application code, an as const object or array plus a derived type is the simplest choice. It adds no generated code and works with ordinary JavaScript tooling.
Exercise
Given const sizes = ["S", "M", "L"] as const;, write a type alias Size that equals "S" | "M" | "L" and is derived from sizes, so that adding a new entry to the array updates Size automatically.
Show answer
type Size = (typeof sizes)[number];. The typeof sizes part gives the type readonly ["S", "M", "L"], and indexing it with number yields the union of all element types.
Exercise
const nums = [1, 2, 3] as const; is passed to function total(values: number[]): number, and the compiler reports an error. Why does it fail, and what is the smallest change to fix it?
Show answer
nums has the type readonly [1, 2, 3], and a readonly array cannot be assigned to a mutable number[] parameter, because the function could modify it. Change the parameter type to readonly number[]. If the function really needs to mutate, pass a copy such as [...nums] instead.