How to concat two different array types that extend/inherit the same type?
Just type assert the first array to a common type of the two array types:
checkOil((<Vehicle[]>buses).concat(trucks));
The casting to <Vehicle[]>
should work
function checkOil(vehicles : Vehicle[]) {}
checkOil((<Vehicle[]>buses).concat(trucks));
Typescript will cast the (busses)
to Vehicle[]
, and the same will be done with the rest
e.g. this will return (in console) two objects - Vehicles
class Vehicle
{
public Type: string;
}
class Bus extends Vehicle
{
public A: string;
}
class Truck extends Vehicle
{
public B: number
}
var buses: Bus[] = [];
buses.push({Type: 'Bus', A : 'A1'});
var trucks: Truck[] = [];
trucks.push({ Type: 'Truck', B: 1 });
function checkOil(vehicles: Vehicle[]) : Vehicle[]
{
return vehicles;
}
var result = checkOil((<Vehicle[]>buses).concat(trucks));
console.log(result)