Sub topic 7
What `as const` cannot do
This chapter assumes you know how as const widens and narrows literals, how it makes objects readonly and arrays into tuples, and how typeof and indexed access derive union types. It covers where the assertion stops working: which expressions it accepts, what it does at runtime (nothing), and where the type system's readonly has gaps.
The assertion applies only to literals
A const assertion is accepted only on a literal expression. Those are string, number, boolean, bigint and template literals, array literals, object literals, and references to enum members. Anything else is a compile error (TS1355).
declare function getName(): string;
const adminName = "admin";
const ok1 = "admin" as const; // "admin"
const ok2 = [1, 2] as const; // readonly [1, 2]
const ok3 = { retries: 3 } as const; // { readonly retries: 3 }
// const bad1 = adminName as const; // error: references to variables are not allowed
// const bad2 = getName() as const; // error: function call results are not allowed
// const bad3 = new Set([1, 2]) as const; // error: not a literalThe assertion changes how the compiler reads a literal. A variable, a call or a constructor result already has a type, so there is nothing to re-read. For adminName, the const declaration already gave it the type "admin".
Non-literal elements stay as they are
The assertion applies to the outer literal. Any element that is not itself a literal keeps its own type.
declare function getName(): string;
declare const count: number;
const mixed = ["fixed", getName(), count] as const;
// readonly ["fixed", string, number]
const user = { kind: "user", name: getName() } as const;
// { readonly kind: "user"; readonly name: string }as const fixes the shape of a value, meaning its length, its keys and its literal members. It cannot narrow a value the compiler only knows as string. If some of your "constants" come from a function, only the literal parts become literal types.
It has no effect at runtime
A type assertion is erased during compilation. The emitted JavaScript contains the plain literal, so the assertion adds no freezing, no copying and no checks.
const settings = { mode: "dark", retries: 3 } as const;The compiler emits this JavaScript:
const settings = { mode: "dark", retries: 3 };The runtime object is an ordinary mutable object. The readonly modifiers and literal types exist only in the type checker's view of it.
Aliases can bypass readonly
TypeScript does not take readonly on object properties into account when checking assignability. A value with readonly properties can be assigned to a variable whose type has mutable properties. Combined with the runtime fact above, that lets the type of a value disagree with its contents.
const settings = { mode: "dark", retries: 3 } as const;
const loose: { mode: string; retries: number } = settings; // compiles
loose.retries = 99;
console.log(settings.retries); // prints 99, although the type says 3The compiler believes settings.retries is 3, and at runtime it is 99. Any narrowing or union derived from that type is now wrong.
Arrays are stricter. A readonly array is not assignable to a mutable array type. The reverse direction is allowed, and it also creates an alias.
const mutable: number[] = [1, 2];
const view: readonly number[] = mutable; // allowed
mutable.push(3);
console.log(view.length); // 3: the "readonly" view changedA readonly type means "I will not write through this reference". It does not mean "nobody will write".
It is not a substitute for `Object.freeze`
If you need the data to be immutable at runtime, you must freeze it. Object.freeze marks an object's own properties as non-writable, and assignments to them then throw a TypeError in strict mode code (modules and classes are always strict). Outside strict mode they are silently ignored.
Object.freeze is shallow. Nested objects stay mutable, and TypeScript's Readonly<T> is shallow too, so the compiler does not warn you.
const base = Object.freeze({ name: "svc", limits: { max: 10 } });
// base.name = "other"; // error: Cannot assign to 'name' because it is a read-only property
base.limits.max = 20; // compiles, and works at runtime
console.log(base.limits.max); // 20Compare this with as const, which is deep at the type level. It marks every nested object and array in the literal as readonly. The two protections therefore cover different layers, and you can combine them with a recursive freeze.
function deepFreeze<T extends object>(value: T): Readonly<T> {
for (const key of Reflect.ownKeys(value)) {
const inner: unknown = Reflect.get(value, key);
if (typeof inner === "object" && inner !== null) {
deepFreeze(inner);
}
}
return Object.freeze(value);
}
const config = deepFreeze({
mode: "dark",
limits: { max: 10 },
} as const);
try {
(config.limits as { max: number }).max = 20; // compiles because of the cast
} catch {
console.log("blocked at runtime");
}
console.log(config.limits.max); // 10The type system gives you compile-time checks on the literal shape, and deepFreeze makes the runtime object match.
You cannot write Object.freeze(x) as const, because a call result is not a literal. Put the assertion on the literal inside the call, as in deepFreeze({ ... } as const) above.
It does not validate data from outside the program
as const describes literals you wrote in source code. Values that arrive at runtime (JSON, form input, environment variables, API responses) have no literal to assert on. JSON.parse returns any, and JSON.parse(text) as const is an error. A plain cast such as JSON.parse(text) as Role compiles but checks nothing.
The pattern is to keep the const array as the single source of truth and check incoming values against it at runtime.
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];
function parseRole(input: string): Role {
const found = ROLES.find((role) => role === input);
if (found === undefined) {
throw new Error(`Unknown role: ${input}`);
}
return found;
}
console.log(parseRole("editor")); // "editor"find returns an element of the tuple, so the result is typed as Role | undefined, and no cast is needed. Compare this with the isRole guard from earlier in the tutorial. That guard needs a cast, (ROLES as readonly string[]), because includes on a tuple of literals only accepts those literals as its argument.
Derived types stay narrow only while you keep them narrow
Once values pass through ordinary array or string methods, the literal information is lost, because those methods return general types.
const ROLES = ["admin", "editor", "viewer"] as const;
const upper = ROLES.map((role) => role.toUpperCase());
// string[]
const copy = [...ROLES];
// ("admin" | "editor" | "viewer")[]
const sorted = [...ROLES].sort();
// ("admin" | "editor" | "viewer")[]
const size = ROLES.length;
// 3Three points follow from this:
- A readonly tuple has no mutating methods, so
ROLES.push("guest")andROLES.sort()are compile errors. Copy it first, as in[...ROLES].sort(). toUpperCase()returnsstring. The compiler does not compute"ADMIN". For that you would need a mapped or template literal type.- Spreading into a new array literal gives a mutable array with a union element type. The tuple's positions and length are gone.
Where the assertion is not allowed
The following table collects the cases covered so far.
| Expression | Allowed with `as const` | Result or reason |
|---|---|---|
| `"a" as const` | Yes | The type is `"a"`. |
| `-1 as const` | Yes | The type is `-1`. |
| `[1, 2] as const` | Yes | The type is `readonly [1, 2]`. |
| `{ a: 1 } as const` | Yes | The type is `{ readonly a: 1 }`. |
| `Color.Red as const` | Yes | An enum member reference is accepted. |
| `someVariable as const` | No | A reference to a variable is not a literal. |
| `getName() as const` | No | A call result is not a literal. |
| `new Set([1]) as const` | No | A constructor call is not a literal. |
| `JSON.parse(text) as const` | No | The value is not known at compile time. |
| `(flag ? "a" : "b") as const` | No | A conditional expression is not a literal. |
For the conditional case, put the assertion on each branch: flag ? ("a" as const) : ("b" as const).
Declaration files and ambient values
You cannot write as const in an ambient declaration, because those contain no expressions. In a .d.ts file, or after a declare const, you describe the type directly with readonly modifiers and literal types.
declare const LEVELS: readonly ["low", "mid", "high"];
type Level = (typeof LEVELS)[number]; // "low" | "mid" | "high"When the compiler emits a .d.ts for your own as const value, it writes this form for you. The consumer sees readonly types and literal types, and the runtime array is still ordinary JavaScript.
Summary of the limits
- Only literal expressions (and enum member references) can be asserted. Variables, calls and constructors cannot.
- Non-literal elements inside an asserted literal keep their original types.
- The assertion is erased at compile time, so the runtime value is unchanged and mutable unless you freeze it.
- Readonly object properties do not block assignment to a mutable type, so aliases can still write.
Object.freezeandReadonly<T>are shallow, whileas constis deep only at the type level.- External data must be checked at runtime. A literal type cannot do that for you.
- Methods such as
mapand the spread operator return wider types.
Exercise
What are the type of view and the printed output in this code, and why does it show a limit of as const?
const cfg = { limit: 5 } as const;
const loose: { limit: number } = cfg;
loose.limit = 10;
const view = cfg.limit;
console.log(view);
Show answer
The type of view is 5, but the program prints 10. The assertion only changes how the compiler sees the literal and is erased in the emitted JavaScript, so cfg is a normal mutable object. TypeScript lets an object with readonly properties be assigned to a type with mutable properties, so loose writes to the same object that cfg points to. The compile-time type and the runtime value now disagree.
Exercise
Which of these lines fail to compile, and why? declare function load(): string; const id = "u1"; const a = id as const; const b = [id, load()] as const; const c = load() as const;
Show answer
Line a compiles only if you treat it as a variable reference: it does not. id as const is an error, because the assertion is not allowed on a reference to a variable. Line c is an error too, because a function call result is not a literal. Line b compiles. It is an array literal, so the assertion is valid, and its type is readonly ["u1", string], where load() keeps the type string.
Exercise
You have const ROLES = ["admin", "editor", "viewer"] as const; and must read a role from a request header at runtime. Why is header as Role a poor choice, and what should you do instead?
Show answer
The cast tells the compiler to trust the value and checks nothing at runtime, so an invalid header would be treated as a valid Role. Check the string against the runtime array, for example with ROLES.find((role) => role === header), and throw or return an error when it is undefined. The array is both the type source and the runtime check.