Difference Between valueof and keyof in TypeScript
Last Updated :
05 Jul, 2024
In TypeScript, valueOf() retrieves the primitive value of an object, useful for accessing inherent data types. Conversely, keyof extracts keys as a union type, crucial for type-safe property referencing and dynamic type handling in TypeScript's type system.
ValueOf() method
The valueOf() method is a built-in method in JavaScript and TypeScript that retrieves the primitive value of a specific object. In TypeScript, this method is typically used with objects that have a defined valueOf() method, such as number objects.
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
The keyof operator in TypeScript is used to extract the keys of a type as a union type. It allows you to access the keys of an object type or an interface, which is useful for scenarios like generic programming and type-safe property accesses.
Syntax:
type KeysOfType = keyof ObjectType;
Example: This example defines an interface Person, a person variable, and a getProperty function. The function retrieves values from the person object using keys, demonstrating type-safe property access.
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 |
---|
These distinctions highlight how valueOf() is used on object instances to retrieve their primitive values, while keyof is employed in TypeScript to manipulate types and ensure type safety in property accesses.
Similar Reads
What is the difference between interface and type in TypeScript ? In TypeScript, both interface and type are used to define the structure of objects, but they differ in flexibility and usage. While interface is extendable and primarily for object shapes, type is more versatile, allowing unions, intersections, and more complex type definitions.Type in TypeScriptThe
3 min read
What is the difference between 'String' and 'string' in TypeScript ? Unlike JavaScript, TypeScript uses static typing, i.e. it specifies what kind of data the variable will be able to hold. Since TypeScript is a superscript of JavaScript, it also holds a distinction between a string and String. The usage of a string object in JS (or TS for that matter) is very minima
4 min read
TypeScript Differences Between Type Aliases and Interfaces Type In TypeScript, both type aliases and interfaces are used to define custom types, but they have distinct differences and use cases.Type Aliases: Allow the definition of types with a custom name, applicable to primitives, unions, tuples, and more complex types. Interfaces: Primarily used for defining
4 min read
Filter a Dictionary by Key or Value in TypeScript Filtering a dictionary by key or value is a common task in TypeScript when working with data structures. TypeScript provides various approaches to achieve this efficiently.Table of Content Using Object.keys() and Array.filter()Using Object.entries() and Array.filter()Using the for...in loopUsing red
3 min read
How to Get an Object Value By Key in TypeScript In TypeScript, we can get an object value by key by accessing the specific properties within the objects of the dynamic type. This can be done using Dot Notation, Bracket Notation, and Optional Chaining. In this article, we will explore all these approaches along with their implementation in terms o
5 min read
How to Get Value of Input in TypeScript ? In TypeScript, retrieving the value of an input element is a common task when building web applications. Whether you're handling form submissions, validating user input, or manipulating data based on user interactions, accessing input values is essential. The below approaches can be utilized to get
2 min read