简体   繁体   English

如何在 Typescript 中初始化类型化数组

[英]How to initialize a typed array in Typescript

I have an array called "cart" of objects which looks like this,我有一个名为“cart”的对象数组,它看起来像这样,

cart:[{name:any, rate:number, qty:number, discount:number, subtotal:number}]

and I don't want to have any data in it at the beginning, but when I write一开始我不想在里面有任何数据,但是当我写的时候

cart:[{name:any, rate:number, qty:number, discount:number, subtotal:number}];

and try to find the length by using并尝试通过使用找到长度

Object.keys(this.cart).length

it shows an error saying它显示一个错误说

`TypeError: Cannot convert undefined or null to object`

Also, how to clear all elements in an Array.另外,如何清除数组中的所有元素。

Based on my understanding, the following should work for you,根据我的理解,以下应该适合你,

interface ISomething {
    name: any;
    rate: number;
    qty: number;
    discount: number;
    subtotal: number
}
let cart: Array<ISomething> = [];

You need to first initialize the array:您需要先初始化数组:

cart = [];

Also, do this to clear all elements in the array.此外,这样做可以清除数组中的所有元素。

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

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