Lookup Types: T[K] After keyof Constraint
What you'll learn: How TypeScript resolves T[K] when K extends keyof T, giving you the property's type.
The Core Idea
When you constrain a type parameter K to keyof T, you're guaranteeing that K is a valid property key of T. Once TypeScript knows this, it can look up what type that property has using the syntax T[K]. This is called a lookup type or indexed access type.
Think of it like this: if T is a filing cabinet and K is a drawer label you're allowed to open (because K extends keyof T), then T[K] tells you what type of documents are inside that specific drawer.
How It Works
When you write a function like this:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
TypeScript performs these steps:
K extends keyof TensuresKis a valid key ofTT[K]looks up the type of the property at that key- The return type becomes that specific property's type
For example:
const person = { name: "Alice", age: 30 };
const personName = getProperty(person, "name"); // Type: string
const personAge = getProperty(person, "age"); // Type: number
TypeScript infers T as { name: string; age: number }, K as "name" or "age", and then resolves T[K] to string or number respectively.
Key Takeaway: T[K] is a lookup type that retrieves the type of property K from object type T, but it only works safely when K extends keyof T guarantees K is a valid key.