Home > Enterprise >  How to initialize an empty array of objects in Typescript?
How to initialize an empty array of objects in Typescript?

Time:08-12

I have fetched a set of data documents, and am looping through them to create an object out of each called 'Item'; each Item object has an 'amount' key and an 'id' key.

I need to append each created Item object to an array called 'Items'. However, when I create this array at the top (currently like this: var itemObjects: [Item]) and then push each item to the array like this:

snapshot.forEach((doc: any) => {
let docData = doc.data()
let items = docData.items
items.forEach((item: any) => {
  let itemObject = new Item(item.amount, item.transactionType)
  console.log("converted item to Item Object:", itemObject)
  itemObjects.push(itemObject)
})

It gives me this error: Unhandled error TypeError: Cannot read properties of undefined (reading 'push')\n

I believe I am incorrectly initializing the variable array up top. Any help is appreciated thanks.

EDIT- the other piece of code (for the Item class) is:

interface IItem {
amount: number
id: string
}

export class Item implements IItem {
 amount: number
 id: string

 constructor(amount: number, id: string) {
  this.amount = amount
  this.id = id
  }
 }

CodePudding user response:

You are not initializing the variable, merely declaring it. After TypeScript removes the type annotations, all that is left in the resulting JavaScript is:

var itemObjects

So just give it a value:

var itemObjects: Item[] = []
                        ^^^^

The other issue (also fixed above) is that [Item] is a tuple of a single Item. At runtime it's just an array, but you can't create one with more or fewer than one Item. Instead, use Item[] to denote an array of items.

CodePudding user response:

You can declare a typed array like the following:

var items = new Array<Item>();

or

var items: Item[] = [];

Both ways will give you exactly same behavior.

Btw why not just use map function instead of forEach?

var items = docs.map((item: any) => new Item(item.amount, item.id));
  • Related