How to reconcile two typed arrays that consist of two different 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 have two typed arrays:

 var buses : Bus[]; var trucks : Truck[]; 

and a function that takes an array of type superclass.

 function checkOil(vehicles : Vehicle[]) {} 

I can transfer to an array of buses or an array of trucks, but I cannot combine them and transfer 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 to combine these arrays?

EDIT: TypeScript Playground

+6
source share
2 answers

Casting on <Vehicle[]> should work

 function checkOil(vehicles : Vehicle[]) {} checkOil((<Vehicle[]>buses).concat(trucks)); 

Typescript will drop (busses) to Vehicle[] , and the same will be done with the rest

eg. this will return (in the 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) 
+5
source

Just enter the first array into the generic type of the two types of arrays:

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

Source: https://habr.com/ru/post/972844/


All Articles