1. Concept library
  2. JavaScript & TypeScript
  3. Module 5: Generics in practice

Concept

keyof constraints

keyof T is the union of the property names of T. With extends, a type parameter can be limited to those keys, so a function that reads obj[key] returns the right type for that key.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what keyof T produces for a given object type
  2. Write a function whose key parameter is constrained with extends keyof T
  3. Predict the return type of obj[key] for a specific key

In practice

A few lines that show keyof constraints doing its job.

TypeScript
function pluck<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const user = { id: 7, name: "Ada", active: true };
const name = pluck(user, "name");     // string
const id = pluck(user, "id");         // number
pluck(user, "email");                 // error: not a key of user

The common mistake

Watch for

Typing the key parameter as string. obj[key] is then an implicit any (or an error under noImplicitAny), and misspelled keys pass the compiler.

What to know first

Your roadmap puts these before keyof constraints, unless you already know them.

How it stays learned

Once a session shows you understand keyof constraints, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

The review card

What you are asked on review day.

JavaScript & TypeScript · Generics in practice

What does `K extends keyof T` constrain?

Show answer

K may only be one of the property names of T — so get<T, K extends keyof T>(obj: T, key: K) rejects keys that do not exist on obj at compile time.

Where it leads

Topics that build on keyof constraints.

Previous in the module← Type parameters