乐闻世界logo
搜索文章和话题

What is the "keyof" operator in TypeScript?

1个答案

1

keyof is a type query operator in TypeScript that retrieves the union of all keys for a given type. This operator is highly useful, especially when creating type-safe code based on object keys.

For example, consider the following Person interface:

typescript
interface Person { name: string; age: number; }

Using keyof Person yields the union type "name" | "age", meaning TypeScript interprets keyof Person as the combination of these two keys.

A common use case for keyof is within functions to restrict parameters to valid object keys. For instance, we can define a function to retrieve an object's property value while ensuring the provided key is valid:

typescript
function getPropertyValue<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } const person: Person = { name: "Alice", age: 25 }; const name = getPropertyValue(person, "name"); // Correct const age = getPropertyValue(person, "age"); // Correct // const location = getPropertyValue(person, "location"); // This line errors because "location" is not a key of `Person`

Here, we define a generic function getPropertyValue that accepts an object obj and a key key. The key key must be a valid key of the object obj's type, enforced by the generic constraint K extends keyof T for type safety. This pattern is invaluable in real-world development, particularly when building reusable and maintainable libraries or APIs.

2024年8月2日 13:55 回复

你的答案