Course contentsShow
← TypeScript
Lesson 567 of 1,79613. GenericsFree lesson

Constraining with keyof

Ensure a type parameter is a key of another type using keyof constraints.

Constraining with keyof

What you'll learn: How to ensure a generic type parameter is a valid key of another type using keyof constraints.


The Core Idea

Sometimes you need to guarantee that a type parameter represents an actual property name of another type. The keyof constraint lets you enforce this relationship, preventing bugs where you might try to access properties that don't exist.

Think of it like a security checkpoint: you're telling TypeScript, "This parameter must be a key that unlocks a door in this specific object type."


How Constraining with keyof Works

When you write <K extends keyof T>, you're saying: "K must be one of the property names that exist on type T."

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

const person = { name: "Alice", age: 30 };

const personName = getProperty(person, "name");  // ✓ Works: "name" is a key
const personAge = getProperty(person, "age");    // ✓ Works: "age" is a key

// getProperty(person, "email");  // ✗ Error: "email" is not a key of person

Without the extends keyof T constraint, TypeScript couldn't verify that key is actually a property of obj, and you'd lose type safety.


Why This Matters

This constraint pattern is fundamental for building type-safe utilities that work with object properties—like plucking values, mapping transformations, or creating proxies. It connects two generic types in a provable relationship.


Key Takeaway: Use extends keyof T to constrain a type parameter to be a valid property key of another type, ensuring compile-time safety when accessing object properties.