liveBook · Manning

As const

As explained in Secrets of the JavaScript Ninja, Third Edition

A TypeScript const assertion that preserves literal types and applies readonly semantics to the asserted literal expression.

`as const` is a TypeScript assertion for object and array literals. It preserves their exact values as types and applies readonly semantics, rather than widening values such as `"str"` to `string`. section 2.1.3 section 10.4.2

Keep an array’s exact values

Without the assertion, `["str", 123]` is inferred as `(string | number)[]`, so its first item has type `string | number`. With `as const`, it becomes the tuple `["str", 123]`, and the first item has type `"str"`. section 2.1.3

Readonly checks are compile-time guards: TypeScript rejects operations such as `push` or assigning to an array item, but the emitted JavaScript array remains mutable. The assertion applies only to object and array literals. section 10.4.2

Listing 10.14 Creating read-only collections in TypeScript
const ninjas = ["Kuma", "Hattori", "Yagyu"] as const;  #A

ninjas.push("Waluigi"); // TypeScript error  #B

type NinjaName = (typeof ninjas)[number];  #C

interface NinjaMetadata {
  homeIsland: string;
}

const ninjaMetadata: ReadonlyMap<NinjaName, NinjaMetadata> =  #D
  new Map(  #D
    Object.entries({  #D
      Kuma: { homeIsland: "Honshu" },  #D
      Hattori: { homeIsland: "Hokkaido" },  #D
    }) as [NinjaName, NinjaMetadata][],  #D
  );  #D

ninjaMetadata.set("Yagyu", {  #E
  homeIsland: "Figi"  #E
}); // TypeScript error  #E

See how a readonly tuple can supply the members of a union type, alongside a separate ReadonlyMap example. section 10.4.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains literal widening, readonly inference, compile-time mutation errors, and derived types; notes runtime mutability and literal-only scope.
Examples
Compares a mixed array with and without `as const` and derives a ninja-name union from a readonly tuple.
What you can do after
Apply `as const` to preserve literal types, reject typed mutations, and derive a union from array elements.
How it connects
Connects literal types and readonly arrays to type narrowing, union types, `keyof`, and ReadonlyMap.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.