简体   繁体   English

TypeScript中包含不同对象的数组

[英]Array with different objects in TypeScript

How can I set a superior class in TypeScript when collecting various different objects in one array that inherit from the same class so that TypeScript doesn't show an error? 在从同一个类继承的一个数组中收集各种不同的对象时,如何在TypeScript中设置一个优等的类,以便TypeScript不显示错误?

I'm trying it like this: 我正在尝试这样:

interface IVehicle{
    modelName: string
}

interface ICar extends IVehicle{
    numberOfDoors: number,
    isDropTop: boolean
}

interface IBike extends IVehicle{
    hasDynamo: boolean
}


var vehicles: IVehicle[] =
    [
        {
            modelName: "carModelName", // Error
            numberOfDoors: 4,
            isDropTop: true
        },
        {
            modelName: "bikeModelName",
            hasDynamo: true
        }
    ]

Doing it this way, I'm getting errors. 这样做,我遇到了错误。

I'm just able to add objects of the superior interface IVehicle if I don't want any errors shown. 如果我不想显示任何错误,我只能添加上级接口IVehicle对象。

After fixing the syntax errors, you can specify the type of each individual entry in the array. 修复语法错误后,您可以指定数组中每个条目的类型。

interface IVehicle {
    modelName: string
}

interface ICar extends IVehicle {
    numberOfDoors: number,
    isDropTop: boolean
}

interface IBike extends IVehicle {
    hasDynamo: boolean
}

let vehicles: IVehicle[] =
    [
        {
            modelName: "carModelName",
            numberOfDoors: 4,
            isDropTop: true,
        } as ICar,
        {
            modelName: "bikeModelName",
            hasDynamo: true
        } as IBike
    ]

Or just change the type of the array to an array of vehicle, car or bike like this: 或者只是将数组的类型更改为车辆,汽车或自行车的数组,如下所示:

let vehicles: Array<IVehicle | ICar | IBike> =
    [
        {
            modelName: "carModelName",
            numberOfDoors: 4,
            isDropTop: true,
        },
        {
            modelName: "bikeModelName",
            hasDynamo: true
        }
    ]

If later you want to determine if an IVehicle is IBike or ICar you can use user defined type guards to do it. 如果以后你要确定一个IVehicleIBikeICAR您可以使用用户定义类型警卫去做。

function isBike(vehicle: IVehicle): vehicle is IBike {
    return (<IBike>vehicle).hasDynamo !== undefined;
}

function isCar(vehicle: IVehicle): vehicle is ICar {
    return (<ICar>vehicle).numberOfDoors !== undefined;
}

function log(vehicle: IVehicle) {
    if (isBike(vehicle)) {
        // tsc knows vehicle is IBike
        console.log(vehicle.hasDynamo);
    } else if (isCar(vehicle)) {
        // tsc knows vehicle is ICar
        console.log(vehicle.numberOfDoors);
    } else {
        console.log(vehicle.modelName);
    }
}

You can read more about them in the Advanced types section of the handbook. 您可以在本手册的“ 高级类型”部分中阅读有关它们的更多信息。

You can also find a working example of the entire code in the playground here . 您还可以在这里找到操场上整个代码的工作示例。

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

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