typescript 如何连接两个不同类型的扩展/继承相同类型的类型化数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24959536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:55:23  来源:igfitidea点击:

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

typescript

提问by daniel.sedlacek

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

编辑:打字稿游乐场

回答by Radim K?hler

The casting to <Vehicle[]>should work

铸造到<Vehicle[]>应该工作

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

打字稿将转换为(busses)to Vehicle[],其余部分也将完成

e.g. this will return (in console) two objects - Vehicles

例如,这将返回(在控制台中)两个对象 - 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)

回答by Ryan Cavanaugh

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

只需将第一个数组类型断言为两种数组类型的公共类型:

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