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;
}
*/
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,
},
];
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;
}
*/
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 š!