TypeScript as const
- Version
- es2025
- Since
- 3.4
- Review
- Draft
Summary#
An as const assertion keeps literal types from widening. Object literal properties become readonly, and array literals become readonly tuples.
Syntax#
const value = literal as const;
Example#
const levels = ["debug", "info", "error"] as const;
type Level = (typeof levels)[number];
function isLevel(value: string): value is Level {
return levels.some((level) => level === value);
}
console.log(isLevel("info"), isLevel("trace"));
const config = { mode: "safe", seen: [] as string[] } as const;
config.seen.push("start");
console.log(config.mode, config.seen.length, Object.isFrozen(config));
Expected output#
true false
safe 1 false
Common mistakes#
as const does not freeze anything at runtime. It also does not make a referenced mutable value deeply readonly, as the seen array shows. Apply it directly to a literal: asserting a variable or a function call result is an error.
Version applicability#
TypeScript 3.4 added const assertions. The assertion is erased from the emitted JavaScript.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0