Keyof Operator

In TypeScript, the keyof operator is used to extract the keys of a type as a union type. It is a type operator that allows you to access the keys of an object type or an interface.

Syntax:

type KeysOfType = keyof ObjectType;

Example: In this example, we define an interface Person with three properties: name, age, and gender. We also define a variable person of type Person with some values. Next, we define a function getProperty that takes an object obj of type T and a key of type K, where K extends keyof T. It means that key must be one of the keys of the object obj. Inside the getProperty function, we simply return the value of obj[key]. Finally, we test the getProperty function by calling it with the person object and various keys such as “name”, “age”, and, “gender”. All three calls are successful as we can see in the output.

Javascript




interface Person {
    name: string;
    age: number;
    gender: string;
}
 
const person: Person = {
    name: "John",
    age: 25,
    gender: "male",
};
 
function getProperty<T, K extends keyof T>(obj: T, key: K) {
    return obj[key];
}
 
console.log(getProperty(person, "name")); // "John"
console.log(getProperty(person, "age")); // 25
console.log(getProperty(person, "gender")); // "male"


Output:

John
25
male

Difference Between valueof and keyof in TypeScript

In this article, we are going to learn the difference between valueOf() and keyof in TypeScript.

Similar Reads

ValueOf() method

The valueOf() method in TypeScript is used to return the primitive value of the specified number object....

Keyof Operator

...

Difference between valueof and keyof in TypeScript

...

Contact Us