Skip to content
dreamcode
dreamcode
Map
Readonly
Lesson 18 of 26
+15 XP on finish
TS ADVANCEDChapter 3 · TS Advanced

Readonly and as const

readonly stops a property from being reassigned, and readonly T[] removes changing methods like push. Writing as const after a literal locks the whole value: every property becomes readonly and every value keeps its exact literal type, so ["north", "south"] as const has the type readonly ["north", "south"]. These checks exist only at compile time; they catch mistakes before the code runs.

Worked example

How it reads

  • config.apiUrl = ... would be a compile error; retries can change
  • as const keeps each direction as its own literal type
  • (typeof DIRECTIONS)[number] turns the array into the union of its values
Cloud tip: The as const array plus [number] pattern gives you a runtime list and a matching type from one source.
index.ts
TYPESCRIPT
type-checked, then run in your browser
Console
Run your code to see its output here.
YOUR TURN

Add as const to LEVELS, create type Level = (typeof LEVELS)[number], and make next take and return a Level. Log next("mid"): high.

Press Run to check your work.