简体   繁体   中英

How to create a class array in typescript/ javascript

I have a class car

export class Car{
    no:number;
    name:string;
}

I want to make a class array of type Car[].

let cars: Car[] = new Car[5];

But this is not possible. I do not want to create arrays of type:

let cars: Array<Cars>

Or

let cars = []

As they make variable of type 'Array' but I want the variable type to be 'Car[]'.

Any help will be appreciable.

You can set the type and declare it as an empty array

let cars: Car[] = [];

Here you have:

class Car extends Array {
    constructor(length: number, public no: number, public name: string) {
        super(length);
    }
}

const cars: Car[] = new Car(6, 42, 'Batman');

Please keep in mind, you problem might be an XY problem.

It is a bad practive to extend native built ins.

I have never used smth like that in my code.

I believe you should not do it either.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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