TypeScript - How to Declare an array of Objects
In this tutorial, we are going to learn about how to declare an array of objects in TypeScript with the help of an examples.
To declare the array of an objects in TypeScript, we can assign the following syntax {}[]
to the variable type.
Now, we can pass array with the multiple objects with the decalred types, here is an example:
Example:
const arr:{user: string, age: number}[] = [
{ user: "Raju", age: 25 },
{ user: "John", age: 27 },
];
In the above code, we have used the inline type declaration to specify the variable with an array of objects where each the object type ‘user’ string and ‘age’ number. So, that we can only pass array with following object key-value pairs.
Declare the array of objects using the Interface
Interfaces in the TypeScript help us to declare the shape of an objects that needs to takes place, by using this we can create an array of objects by specifying the types in the Interface.
Here is an example:
interface User {
user : string;
age : number;
}
const arr : User[] = [
{ user: "Raju", age: 25 },
{ user: "John", age: 27 },
]
If you try to pass any other key value pair to the object that is not specified in the Interface, we will get the following error in the console.
const arr : User[] = [
{ user: "Raju", age: 25 , total : 100}
]
Error :
Object literal may only specify known properties, and
'total' does not exist in type 'User'.