as const as const Assertion
Last updated: 2026-10-22
as const as const Assertion
as const freezes a literal into its deepest constant type: every property becomes readonly, every value narrows to its literal type (string, number, boolean), and arrays become readonly tuples. It is the core of the classic pattern of deriving union types from a constant table.
| Group | Narrowing & Assertions |
|---|---|
| Kind | Operator |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number]; // "admin" | "editor" | "viewer"
const THEME = { mode: "dark", fontSize: 14 } as const;
// { readonly mode: "dark"; readonly fontSize: 14 }
⚙️ Parameters
| as const | Applied to a literal expression: infers the narrowest readonly literal types instead of the default wide ones (string, number, mutable arrays) |
|---|
Returns:No runtime effect — as const vanishes after transpilation; it only swaps the inferred compile-time type for its narrowest readonly version.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
admin/editor/viewer
role set to editor
dark 14
(Runtime output after transpilation. setRole("editor") passes because as const turns Role into a literal union — without as const, ROLES infers as string[] and setRole("editor") fails to compile)
💡 Notes
ℹ️ Info as const is deep: nested properties also become readonly and narrow to literals. This differs from Readonly<T>, which is shallow.
⚠️ Note After as const no property can be reassigned and arrays cannot be pushed to — compile-time errors. Build a mutable copy with spread: { ...DEFAULT_THEME, mode: "light" }.
💡 Tip Classic combo: (typeof CONST)[number] turns an as const array into a literal union, making the constant table the single source of truth — add a role and the type follows automatically.
🏷️ Related Narrowing & Assertions
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q How is a const variable different from as const?
A const only prevents reassigning the variable — object properties stay mutable and inference stays wide (string); as const narrows the type itself to readonly literals. const locks the binding, as const locks the type.
Q How do I derive a union type from an as const array?
A Two steps: typeof ARR gets the array type, then the indexed access [number] unions all element types: type Role = (typeof ROLES)[number]. This official pattern avoids maintaining two lists.
Q Should every object literal get as const?
A No. It fits genuine constants: config snapshots, enum value tables, action types. Objects that will be mutated or filled from mutable state should not use it — you would just fight readonly errors and pile up assertions.