Open In App

How to Create a Typed Array from an Object with Keys in TypeScript?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript, we can create a typed array from an object with keys by extracting the keys and then mapping them to the desired array type. This mainly makes sure that type of safety is preserved.

Below are the approaches used to create a Typed Array from an Object with Keys in TypeScript:

Approach 1: Using Object.keys() and map method

Here we use the Object.key() method to extract an array of keys from the object and by using the map() method to create a typed array by accessing the values using keys.

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.

Javascript




const arr = {
  name: "GeeksforGeeks",
  category: "Programming",
  founded: 2009,
};
const keyArr: (keyof typeof arr)[] =
    Object.keys(arr) as (keyof typeof arr)[];
const typeArr: (string | number)[] =
    keyArr.map(key => arr[key]);
console.log(typeArr);


Output:

["GeeksforGeeks", "Programming", 2009] 

Approach 2: Using Object.entries() and map method

Here we use the Object.entries() method to retrieve an array of ‘[key, value]’ pairs from the object, and then uses the map method to create a typed array by extracting the values.

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.

Javascript




const arr = {
    name: "GeeksforGeeks",
    category: "Programming",
    founded: 2009,
  };
const typeArr: (string | number)[] = Object
      .entries(arr).map(([key, value]) => value);
console.log(typeArr);


Output:

["GeeksforGeeks", "Programming", 2009] 

Approach 3: Using Object.getOwnPropertyNames() method

Here we use the Object.getOwnPropertyNames() method to get an array of all property names from the object and then the map method creates a typed array by accessing the corresponding values through the property names.

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.

Javascript




const arr = {
    name: "GeeksforGeeks",
    category: "Programming",
    founded: 2009,
  };
const typeArr: (string | number)[] = Object
      .getOwnPropertyNames(arr).map(key =>
        arr[key as keyof typeof arr]);
console.log(typeArr);


Output:

["GeeksforGeeks", "Programming", 2009] 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads