Const assertions
Concept and syntax
An as const assertion on a literal expression preserves literal types, gives object literal properties readonly types, and gives array literals readonly tuple types. This helps describe exact configuration values. It is not Object.freeze and does not freeze objects at runtime. Referenced objects can remain mutable; the assertion applies to the literal structure, not every reachable object.
Working example
Compile standalone examples in a fresh directory with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
const settings = { mode: "light", nested: { count: 2 } } as const;const mode: "light" = settings.mode;const sharedValues = [1];const wrapper = { sharedValues } as const;wrapper.sharedValues.push(2);console.log(mode, settings.nested.count, sharedValues.length);Expected output (one line per log):
light 2 2Common mistake
Intentionally invalid; check this snippet separately. Do not run it.
const settings = { mode: "light" } as const;settings.mode = "dark";Expected compiler diagnostic: TS2540. A const assertion gives this property a readonly type. Create a new object when the configuration should change.
Practice and recap
Try assigning a different value to the nested count, then mutate the separately referenced array. Explain why these checks differ.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Const assertions — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
What does as const do to an array literal?
Can a referenced mutable array inside an as const object still be mutated?
What prevents settings.mode from being assigned?
const settings = { mode: "light" } as const;settings.mode = "dark";