daniel.sedlacek
daniel.sedlacek

Reputation: 8629

How to concat two different array types that extend/inherit the same type?

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

Upvotes: 12

Views: 24385

Answers (2)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220964

Just type assert the first array to a common type of the two array types:

checkOil((<Vehicle[]>buses).concat(trucks));

Upvotes: 4

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123861

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)

Upvotes: 14

Related Questions