DEV Community

Cover image for How to get the object type from an array of objects in TypeScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to get the object type from an array of objects in TypeScript?

Originally posted here!

To get the object type from an array of objects first, we can use the typeof type operator followed by the array variable name or array literal followed by writing a square brackets symbol ([]) and inside the square brackets, we can write the type number to get the type of array's elements.

TL;DR

// an array of objects
const arrOfObjs = [
  {
    name: "Lily Roy",
    isAdmin: true,
    age: 29,
  },
  {
    name: "John Doe",
    isAdmin: false,
    age: 23,
  },
  {
    name: "Roy Daniels",
    isAdmin: true,
    age: 25,
  },
];

// get the type of the object inside
// the array `arrOfObjs`
type ArrObj = typeof arrOfObjs[number];

/*
👆 If you hover over the `ArrObj` type you will see this,

type ArrObj = {
    name: string;
    isAdmin: boolean;
    age: number;
}
*/
Enter fullscreen mode Exit fullscreen mode

For example, let's say we have an array of objects like this,

// an array of objects
const arrOfObjs = [
  {
    name: "Lily Roy",
    isAdmin: true,
    age: 29,
  },
  {
    name: "John Doe",
    isAdmin: false,
    age: 23,
  },
  {
    name: "Roy Daniels",
    isAdmin: true,
    age: 25,
  },
];
Enter fullscreen mode Exit fullscreen mode

Now to get the type of the object in the above array of objects first, we can use the typeof type operator followed by the array variable name in our case arrOfObjs followed by writing a square brackets symbol ([]) and inside the square brackets, we can write the type number to get the type of array's object elements.

It can be done like this,

// an array of objects
const arrOfObjs = [
  {
    name: "Lily Roy",
    isAdmin: true,
    age: 29,
  },
  {
    name: "John Doe",
    isAdmin: false,
    age: 23,
  },
  {
    name: "Roy Daniels",
    isAdmin: true,
    age: 25,
  },
];

// get the type of the object inside
// the array `arrOfObjs`
type ArrObj = typeof arrOfObjs[number];

/*
👆 If you hover over the `ArrObj` type you will see this,

type ArrObj = {
    name: string;
    isAdmin: boolean;
    age: number;
}
*/
Enter fullscreen mode Exit fullscreen mode

Now if you hover over the ArrObj type you can see that this is now a type that consists of properties like name, isAdmin, and age having the types of string, boolean, and number respectively which is exactly what we want to happen.

We have successfully got the object type from an array of objects in TypeScript. Yay 🥳!

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.


Top comments (0)