![]() |
Creating a typed array from the keys of an object in TypeScript ensures that your application maintains type safety, particularly when interacting with object properties. Here we’ll explore different approaches to achieve this using TypeScript’s built-in Object methods. Below are the approaches used to create a Typed Array from an Object with Keys in TypeScript: Table of Content 1. Using Object.keys() and map methodThe Object.keys() method is used to extract keys from an object, and the map method is then used to iterate over these keys to access corresponding values. Syntax:const newArray: string[] = Object.keys(obj).map((key) => obj[key]); Example: The below code explains the use of Object.keys() and map method to create a typed array from an object with keys in Typescript.
Output:["GeeksforGeeks", "Programming", 2009] 2. Using Object.entries() and map methodObject.entries() retrieves key-value pairs as an array, and values are then accessed using the map method. Syntax:const newArray: string[] = Object.entries(obj).map(([key, value]) => value); Example: The below code explains the use of Object.entries() and map method to create a typed array from an object with keys in Typescript.
Output:["GeeksforGeeks", "Programming", 2009] 3. Using Object.getOwnPropertyNames() methodThis method is particularly useful for retrieving all property names (including non-enumerable ones) from an object. Syntax:const newArray: string[] = Object.getOwnPropertyNames(obj).map(key => obj[key]); Example: The below code explains the use of the Object.getOwnPropertyNames() method to create a typed array from an object with keys in Typescript.
Output:["GeeksforGeeks", "Programming", 2009] Using Object.values() MethodThe Object.values() method returns an array of a given object’s own enumerable property values. We can utilize this method to directly extract the values of the object and create a typed array from them. Syntax:const newArray: ValueType[] = Object.values(obj); Example: The following code demonstrates how to use Object.values() to create a typed array from an object with keys in TypeScript.
Output: ["GeeksforGeeks", "Programming", 2009] Each method has its own strengths and can be chosen based on what best fits your needs, whether it’s simplicity, compatibility with non-enumerable properties, or the need to manipulate both keys and values. These techniques ensure that your TypeScript code remains clean, efficient, and type-safe. |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |