Author -  Sai gowtham

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'.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY