The Classic Property Getter Pattern
You'll learn how to write a type-safe function that retrieves a property value from an object using generic constraints.
The Core Idea
JavaScript lets you access object properties like person["name"], but TypeScript doesn't know if that property actually exists. The classic property getter pattern uses <T, K extends keyof T> to guarantee:
- The key you're asking for actually exists on the object
- The return type matches the property's value type
This pattern combines two concepts you've learned: generic type parameters and keyof constraints.
How It Works
When you write a generic function with two type parameters like this:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
You're saying:
Tis the type of the objectKis constrained to be only keys that exist onT- The return type
T[K]is the type of that specific property
This creates a relationship where the second type parameter depends on the first one.
Why This Matters
Without this pattern, you'd either use any (losing type safety) or get errors when accessing dynamic properties. With it, TypeScript prevents you from requesting properties that don't exist and accurately types what you get back.
Think of it like a vending machine that only accepts coin slots that actually exist on that specific machine—and guarantees you get exactly the snack labeled at that slot.
Key Takeaway: The <T, K extends keyof T> pattern creates a type-safe property accessor where the key parameter is constrained to actual properties of the object, and the return type automatically matches the property's type.