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:
  1. key must be an actual property of obj
  2. 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!

Please set the playground first

Loading "Generic Constraints"
Loading "Generic Constraints"
Login to get access to the exclusive discord channel.
Loading Discord Posts