Open In App

Difference Between valueof and keyof in TypeScript

Last Updated : 09 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

ValueOf() method

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

Syntax:

number.valueOf();

Example 1: In this example, we have used the ValueOf() method.

Javascript




// valueOf()
let num = new Number(30);
console.log(num.valueOf());


Output:

30

Example 2: In this example, we have used the valueOf() method.

Javascript




// valueOf() method
let num4 = new Number(563);
console.log("Number Method: tovalueOf()");
console.log(typeof num4 )
console.log(num4 )
console.log(num4 .valueOf())


Output:

Number Method: tovalueOf()
number
[Number: 563]
563

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

Feature valueOf keyof
Purpose Obtains the primitive value of an object Obtains a union type of property names
Usage Object instance method TypeScript operator in type definitions
Example typescript class MyObject { valueOf() { return this.value; } } typescript type MyType = { name: string; age: number; city: string; }; type MyKeys = keyof MyType;
Applicability General JavaScript usage, not specific to TypeScript TypeScript-specific, particularly useful in generic programming scenarios
Return Type Typically returns a primitive value (e.g., number, string) Returns a union type of all property names


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads