I have two classes that inherit from the same superclass:
class Vehicle {}
class Bus extends Vehicle {}
class Truck extends Vehicle {}
Let's have two typed arrays:
var buses : Bus[];
var trucks : Truck[];
and a function that accepts an array of the superclass type.
function checkOil(vehicles : Vehicle[]) {}
I can pass in array of busses or array of trucks but I can not merge them and pass them together:
function checkOil(buses.concat(trucks));
//error TS2082: Supplied parameters do not match any signature of call target:
Types of property 'pop' of types 'Bus[]' and 'Track[]' are incompatible:
How do I merge those arrays?
EDIT: TypeScript Playground
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)
Just type assert the first array to a common type of the two array types:
checkOil((<Vehicle[]>buses).concat(trucks));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With