TypeScript Reference ยท Type Operators
TypeScript as const assertions
Reference for as const in TypeScript: infer literal, readonly types for arrays and objects, derive unions from values, and combine it with satisfies.
as const is a special type assertion that asks the compiler to infer the narrowest type for a value. String, number and boolean literals keep their exact values, object properties become readonly, and array literals become readonly tuples with fixed length and positions.
Without it, ["a", "b"] is string[] and { mode: "dark" } is { mode: string }. With it you get readonly ["a", "b"] and { readonly mode: "dark" }. It is the easiest way to derive union types from runtime data.
const roles = ["admin", "user"] as const; type Role = (typeof roles)[number]; // "admin" | "user"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
const value = expression as const;
| Applied to | Result |
|---|---|
| String, number, boolean, bigint literal | The literal type ("a", 3, true). |
| Template literal without substitutions | The literal string type. |
| Array literal | readonly tuple of the element types. |
| Object literal | Object with readonly properties; nested literals are also const-ified. |
Errors and edge cases:
- It can only be applied directly to literal expressions (and enum members).
x as constwherexis a variable is an error: "A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals." - The
readonlyis compile-time only. The runtime object is mutable unless you also callObject.freeze. - A readonly array is not assignable to a mutable
string[]parameter. Declare the parameterreadonly string[].
Usage notes
- Unions from arrays:
(typeof list)[number]is the idiom. See indexed access types. - Replaces enums for simple cases: a const object plus a derived type has no runtime enum machinery.
- Deep: nested objects and arrays are all made readonly.
- Computed values (function calls, variables) are not narrowed; only literals are.
consttype parameters (TypeScript 5.0) apply the same idea to generics; see const type parameters.- Combine with
satisfies: writeas const satisfies T, in that order. - Declared
let:let x = "a" as constgives type"a"and cannot be reassigned to another string.