How to use the built-in Array type In Typescript
We can also use the built-in Array type to define an array of object in TypeScript.
Syntax:
const array_name: Array<{key1: type1, key2: type2, key3: type3}> = [{}];
Example: This example will show you the use of the Array type to create an array of object in TypeScript.
let myArr: Array<{
cktr_name: string,
cktr_team: string, cktr_runs: number
}> = [
{
cktr_name: "Virat Kohli",
cktr_team: "India",
cktr_runs: 26000
},
{
cktr_name: "AB De Villiers",
cktr_team: "South Africa",
cktr_runs: 15000
},
{
cktr_name: "David Warner",
cktr_team: "Australia",
cktr_runs: 13000
}
];
myArr.forEach((cktr) => {
console.log(`Hi, My name is ${cktr.cktr_name},
I play for ${cktr.cktr_team} and
I've already made ${cktr.cktr_runs}
runs while representing my country.`)
})
Output:
Hi, My name is Virat Kohli, I play for India and I've already made 26000 runs while representing my country.
Hi, My name is AB De Villiers, I play for South Africa and I've already made 15000 runs while representing my country.
Hi, My name is David Warner, I play for Australia and I've already made 13000 runs while representing my country.
How can I Define an Array of Objects in TypeScript?
In TypeScript, the way of defining the arrays of objects is different from JavaScript. Because we need to explicitly type the array at the time of declaration that it will be an Array of objects. In this article, we will discuss the different methods for declaring an array of objects in TypeScript.
There are many methods of declaring an array of objects in TypeScript as listed below:
Table of Content
- Using the inline type declaration
- Using the in-built interfaces and type
- Using the built-in Array type
- Using the typeof operator
- Using Mapped Types and Generics