Array with various objects in TypeScript

How can I set a different class in TypeScript when collecting different objects in the same array that inherit from the same class so that TypeScript doesn't display an error?

I try 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
        }
    ]

      

While doing this I am getting errors.

I can just add superior interface objects IVehicle

if I don't want to show any errors.

+3


source to share


1 answer


After fixing 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 car, car, or bike like this:

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

      



If you later want to determine if the IVehicle is IBike or ICar , you can use user protected protection types. p>

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 section Extended types in the reference.

You can also find a working example of all the playground code here .

+8


source







All Articles