The ‘keyof‘ operator in TypeScript is a type operator that returns a union type of all the possible keys (strings, numbers, or symbols) that can be used to access properties of a given typed object. It’s particularly useful when you want to create a function that can take an object and a key of that object, and TypeScript can enforce that the key provided exists on the object.
Here’s an example of how you can use the ‘keyof‘ operator:
Suppose you have a simple ‘Person‘ interface:
interface Person {
id: number;
name: string;
age: number;
}
Now, let’s create a ‘getProperty‘ function that returns the value of a key in a given object of type ‘Person‘.
function getProperty(person: Person, key: keyof Person): any {
return person[key];
}
The ‘key: keyof Person‘ parameter ensures that the ‘key‘ argument passed to the ‘getProperty‘ function is one of the valid keys of a ‘Person‘ object (i.e., ‘"id"`, ‘"name"`, or ‘"age"`).
This function implementation uses the ‘keyof‘ operator to make sure that the passed key is a valid key for the given ‘Person‘ object.
Here’s an example of how the ‘getProperty‘ function can be used:
const tom: Person = {
id: 1,
name: "Tom",
age: 25,
};
console.log(getProperty(tom, "name")); // Output: "Tom"
console.log(getProperty(tom, "age")); // Output: 25
// This line would cause a TypeScript error: Argument of type '"invalid_key"' is not assignable to parameter of type 'keyof Person'.
//console.log(getProperty(tom, "invalid_key"));
Notice how the invalid key ‘"invalid_key"` would cause an error in TypeScript if it were not commented out. This is because the ‘keyof‘ operator ensures that only valid keys can be used.
To summarize, the ‘keyof‘ operator in TypeScript helps in creating type-safe code by enforcing that only valid keys are used to access properties of a given typed object.