Generic Constraints
Constraints (π solution)
π¨βπΌ You've mastered generic constraints!
π¦ The
keyof constraint pattern is incredibly powerful:function getProperty<ObjectType, Key extends keyof ObjectType>(
obj: ObjectType,
key: Key,
): ObjectType[Key]
This ensures:
keymust be an actual property ofobj- The return type matches the property's type exactly
const user = { name: 'Alice', age: 30 }
getProperty(user, 'name') // Returns string
getProperty(user, 'age') // Returns number
getProperty(user, 'foo') // β Error: 'foo' is not a key of user
This is how TypeScript's built-in
Pick, Omit, and other utility types work
under the hood!