The keyof operator is a powerful feature in TypeScript that allows you to extract the key type from an object type. It's essential for creating flexible and type-safe code when working with object properties.
keyof produces a union type of all the keys in an object type. This is particularly useful when you need to ensure type safety while accessing object properties dynamically.
Here's the basic syntax for using the keyof operator:
type Keys = keyof ObjectType;
Let's look at a practical example:
interface User {
name: string;
age: number;
email: string;
}
type UserKeys = keyof User; // "name" | "age" | "email"
function getProperty(user: User, key: UserKeys) {
return user[key];
}
const user: User = {
name: "Alice",
age: 30,
email: "alice@example.com"
};
console.log(getProperty(user, "name")); // Output: Alice
// console.log(getProperty(user, "address")); // Error: Argument of type '"address"' is not assignable to parameter of type 'keyof User'.
The keyof operator ensures that you can only access properties that exist on an object:
function pluck<T, K extends keyof T>(obj: T, keys: K[]): T[K][] {
return keys.map(key => obj[key]);
}
const car = { make: "Toyota", model: "Corolla", year: 2021 };
console.log(pluck(car, ["make", "model"])); // Output: ["Toyota", "Corolla"]
// console.log(pluck(car, ["make", "color"])); // Error: Argument of type '"color"' is not assignable to parameter of type 'keyof { make: string; model: string; year: number; }'.
keyof is often used with mapped types to create new types based on existing ones:
type Optional<T> = {
[K in keyof T]?: T[K];
};
interface Product {
id: number;
name: string;
price: number;
}
type OptionalProduct = Optional<Product>;
// Equivalent to:
// {
// id?: number;
// name?: string;
// price?: number;
// }
keyof to create more flexible and reusable functions that work with object properties.keyof with Generics in TypeScript for maximum flexibility.keyof only works with known keys at compile-time. It doesn't capture dynamically added properties.keyof with Union Types, the result will be a union of all possible keys.To further enhance your understanding of TypeScript's type system, explore these related topics:
By mastering the keyof operator, you'll be able to write more robust and type-safe TypeScript code, especially when dealing with dynamic property access and creating flexible type transformations.