我遇到了以下不寻常的情况:
我有两个模型,为了这个讨论的目的,让他们是Car和Spaceship。
我编写了一个具有由以下约束定义的输入的组件:这个输入是一个数组,可以是Car或Spaceship,,但不能同时使用。因此,产生以下代码:
@Component({
selector: 'app-stack-example',
...
})
export class StackExample{
@Input() listOfVehicles: Array<Car> | Array<Spaceship> = [];
...
}据我理解,这应该是有效的代码,因为我从来不希望它接收一个混合数组。在对设置为这样的输入执行了一些dev之后,我遇到了以下问题:
在以任何方式修改/访问数组时(push()、splice()、indexOf()、find()、findIndex()等),例如:
this.listOfVehicles.push(new Car());我得到以下错误:
TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((...items: Car[]) => number) | ((...items: Spaceship[]) => number)' has no compatible call signatures.为什么会发生这种情况?
发布于 2018-03-25 17:08:21
从代码中编译器不清楚数组当前的类型。因此,在对数组使用函数之前,您可能必须检查类型或将数组转换为这两种数组类型之一。
实际上,您的参数不能同时分配给push(item: Car)和push(item: Spaceship)这两种可能的类型。
https://stackoverflow.com/questions/49478466
复制相似问题