Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a typed array in Typescript

I have an array called "cart" of objects which looks like this,

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.

like image 953
Kedar Udupa Avatar asked Sep 02 '25 16:09

Kedar Udupa


1 Answers

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> = [];
like image 200
Muthukumar Avatar answered Sep 04 '25 05:09

Muthukumar