I came across the following unusual scenario:
I have two models, for the purposes of this discussion, let them be Car and Spaceship.
I wrote a component with an input defined by the following constraint: This input is an array that can either be of type Car or Spaceship, but not both. Thus, producing the following code:
@Component({
selector: 'app-stack-example',
...
})
export class StackExample{
@Input() listOfVehicles: Array<Car> | Array<Spaceship> = [];
...
}
From my understanding this should be valid code, since I never want it to receive a mixed array. After doing some dev with the input set up as such, I ran into the following issue:
When modifying/accessing the array in any way (push(), splice(), indexOf(), find(), findIndex(), etc), eg:
this.listOfVehicles.push(new Car());
I get the following error:
TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((...items: Car[]) => number) | ((...items: Spaceship[]) => number)' has no compatible call signatures.
Why does this occur?
pushan instance of typeCaryou needlistOfVehiclesto be of concrete typeArray<Car>, which is not guaranteed by the type oflistOfVehiclesas you define it.Vehicleand then have bothCarandSpaceshipextend it, and makelistOfVehiclesof typeArray<Vehicle>.