AI Hints
Home›TypeScript Tutorial›Generics Practice and keyof
TypeScript · Lesson 60 of 120

keyof

The keys as a type.

⏱ 2 min read▶ Video at 46:56🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Keyof takes an object type, and gives a union of its property names. That lets functions accept only real property names, never typos.

keyof
From the video: keyof
  • An object type
  • Its property names
  • A union

A safe property reader

Keyof bike is the union of model, price, and stock. Get field takes a bike and one of those keys. The return type even matches the property. Run it.

app.tstypescript
type Bike = { model: string; price: number; stock: number };
type BikeKey = keyof Bike;   // "model" | "price" | "stock"

function getField<K extends keyof Bike>(bike: Bike, key: K): Bike[K] {
  return bike[key];
}

const b: Bike = { model: "Trail 500", price: 849.5, stock: 12 };
console.log(getField(b, "model"), getField(b, "price"));
Output
Trail 500 849.5

No typos

Here the key is misspelled. Run it. Only real property names are allowed.

app.tstypescript
type Bike = { model: string; price: number };
function getField<K extends keyof Bike>(bike: Bike, key: K) { return bike[key]; }
getField({ model: "Trail 500", price: 849.5 }, "prise");
Output
app.ts line 3: Argument of type '"prise"' is not assignable to parameter of type 'keyof Bike'.

Summary

Keyof turns property names into a union type, so keys are always checked. Next, typeof types.

Key takeaways
  • keyof Bike
  • K extends keyof T
  • No typos
Next up: typeof Types — types from values