Skip to content
Tutorials Center
My learning

Topics

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.

TypeScript
const roles = ["admin", "user"] as const;
type Role = (typeof roles)[number]; // "admin" | "user"

Try it

TypeScript Literals, tuples and readonly

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.

TypeScript Derive unions from data

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

TypeScript
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 const where x is 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 readonly is compile-time only. The runtime object is mutable unless you also call Object.freeze.
  • A readonly array is not assignable to a mutable string[] parameter. Declare the parameter readonly 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.
  • const type parameters (TypeScript 5.0) apply the same idea to generics; see const type parameters.
  • Combine with satisfies: write as const satisfies T, in that order.
  • Declared let: let x = "a" as const gives type "a" and cannot be reassigned to another string.