What keyof Does: Extracting Keys as a Union
You'll learn: How to use keyof to turn an object type's property names into a literal union type.
When you're working with generic constraints, you often need to reference the keys of an object type. The keyof operator extracts all property names from a type and creates a union of string literals representing those keys.
The Core Concept
Think of keyof as asking TypeScript: "What are all the valid property names for this type?" TypeScript responds by giving you a union of literal types—one for each key.
type Person = {
name: string;
age: number;
email: string;
};
type PersonKeys = keyof Person;
// PersonKeys is now: "name" | "age" | "email"
How It Works
The keyof operator transforms an object type into a union type. Each property name becomes a string literal type in that union:
type Product = {
id: number;
price: number;
};
type ProductKey = keyof Product;
// ProductKey is: "id" | "price"
const validKey: ProductKey = "id"; // ✓ OK
const invalidKey: ProductKey = "name"; // ✗ Error
Why This Matters for Generics
The power of keyof becomes clear when combined with generic constraints. You can ensure a parameter is actually a key that exists on a type:
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
const user = { name: "Alice", age: 30 };
getProperty(user, "name"); // ✓ OK
getProperty(user, "salary"); // ✗ Error: "salary" not in keyof user
Key Takeaway: keyof T extracts all property keys from type T as a union of literal types, enabling type-safe access to object properties in generic code.