Rectifying the syntax errors allows you to specify the type of each element in the array individually.
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
]
Alternatively, you can simply 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 at a later point you need to determine whether an IVehicle is actually an IBike or ICar, you can utilize user-defined type guards for this purpose.
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)) {
// TypeScript compiler recognizes vehicle as IBike
console.log(vehicle.hasDynamo);
} else if (isCar(vehicle)) {
// TypeScript compiler recognizes vehicle as ICar
console.log(vehicle.numberOfDoors);
} else {
console.log(vehicle.modelName);
}
}
For more information on this topic, refer to the User-Defined Type Guards section in the handbook.
To see a complete working example of the code provided, visit the playground here.