How to Use the keyof Operator in TypeScript

The keyof operator in TypeScript is a useful way to index the types of an object. This operator can be used to extract the types of the keys of an object, creating a union type that represents the possible key names for the object.

To see how this works, let's consider the following example:

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

Here, we have defined an object called person that has two properties: name and age. We can use the keyof operator to extract the type of the keys of this object, like this:

keyof person // "name" | "age"

As you can see, the keyof operator creates a union type that represents either the string "name" or the string "age". This type is useful because it allows us to constrain the type of a variable to be one of the possible key names for the person object.

Here's an example of how you might use the keyof operator in a type assertion:

function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
const name = getProperty(person, "name"); // name has type string

In this example, we have defined a generic function called getProperty() that takes an object obj and a key key, and returns the value of the property with the specified key from the object. The type of the key parameter is constrained using the keyof operator, so that it must be a key of the obj parameter. This ensures that the key parameter will always be a valid property name for the obj parameter.

In summary, the keyof operator is a powerful tool for working with the types of objects in TypeScript. It allows you to extract the types of an object's keys and use them to constrain the types of variables. This can help you write safer and more type-safe code.


December 10, 2022
1009