Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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

like image 412
daniel.sedlacek Avatar asked Jul 25 '14 15:07

daniel.sedlacek


2 Answers

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)
like image 68
Radim Köhler Avatar answered Oct 16 '22 21:10

Radim Köhler


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

checkOil((<Vehicle[]>buses).concat(trucks));
like image 30
Ryan Cavanaugh Avatar answered Oct 16 '22 20:10

Ryan Cavanaugh