简体   繁体   English

如何在 Typescript 中初始化一个空的对象数组?

[英]How to initialize an empty array of objects in Typescript?

I have fetched a set of data documents, and am looping through them to create an object out of each called 'Item';我已经获取了一组数据文档,并且正在循环它们以从每个称为“项目”的每个文件中创建一个 object; each Item object has an 'amount' key and an 'id' key.每个项目 object 都有一个“金额”键和一个“ID”键。

I need to append each created Item object to an array called 'Items'.我需要将 append 每个创建的项目 object 到一个名为“项目”的数组中。 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:但是,当我在顶部创建这个数组时(目前像这样: var itemObjects: [Item] ),然后像这样将每个项目推送到数组中:

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它给了我这个错误:未处理的错误类型错误:无法读取未定义的属性(读取“推送”)\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:编辑-另一段代码(用于 Item 类)是:

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
  }
 }

You are not initializing the variable, merely declaring it.您没有初始化变量,只是声明它。 After TypeScript removes the type annotations, all that is left in the resulting JavaScript is:在 TypeScript 删除类型注释之后,生成的 JavaScript 中剩下的就是:

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 .另一个问题(上面也解决了)是[Item]是单个Item元组 At runtime it's just an array, but you can't create one with more or fewer than one Item .在运行时它只是一个数组,但您不能创建一个多于或少于一个Item的数组。 Instead, use Item[] to denote an array of items.相反,使用Item[]来表示一个项目数组。

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?顺便说一句,为什么不只使用 map function 而不是 forEach?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM