`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
