Skip to content
dreamcode
dreamcode
Map
keyof & typeof
Lesson 15 of 26
+15 XP on finish
TS ADVANCEDChapter 3 · TS Advanced

keyof and typeof

keyof T is the union of a type's property names: keyof { a: number; b: string } is "a" | "b". In a type position, typeof value gives you the type of a real value. Together they derive types from your data instead of writing them twice, so the types update automatically when the data changes.

Worked example

How it reads

  • typeof palette copies the object's shape into a type
  • keyof turns that shape into "dusk" | "dawn" | "night"
  • Add a color to the object and ColorName grows by itself
Cloud tip: Object.keys always returns string[]. Cast it with as (keyof T)[] only when you know the object has no extra keys.
index.ts
TYPESCRIPT
type-checked, then run in your browser
Console
Run your code to see its output here.
YOUR TURN

Type the parameter as keyof typeof settings and return settings[key], so read("theme") logs dark.

Press Run to check your work.