Combining keyof with Generics for Object Manipulation
You'll learn: How to build type-safe utility functions like pick or pluck that extract properties from objects while preserving full type information.
The Power of Combining Forces
You've learned keyof extracts object keys as a union type, and you've seen how generics make functions reusable. Now we combine them to create powerful object manipulation utilities that guarantee the keys you access actually exist.
Think of it like a smart librarian: instead of just trusting you when you ask for a book, they verify it's actually in their catalog before retrieving it.
Building Type-Safe Utilities
When you combine keyof with generics, you can enforce that a key parameter must be a key of the object you're working with:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { name: "Alice", age: 30 };
const userName = getProperty(user, "name"); // string
const userAge = getProperty(user, "age"); // number
// getProperty(user, "email"); // ❌ Error: "email" not in keyof typeof user
Notice how K extends keyof T ensures key is valid, and the return type T[K] automatically infers the property's type.
The pick Pattern
You can extend this to select multiple properties:
function pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
const result = {} as Pick<T, K>;
for (const key of keys) {
result[key] = obj[key];
}
return result;
}
const user = { name: "Bob", age: 25, email: "bob@test.com" };
const subset = pick(user, ["name", "age"]); // { name: string; age: number }
Key Takeaway: Combining keyof with generic constraints lets you build utilities that manipulate objects with complete compile-time safety—the compiler verifies every key exists and preserves exact property types.