I have an interface (Vehicle
), a class that implements it (Car
) and has some method (isColorRed
):
export interface Vehicle{
color : string;
}
export class Car implements Vehicle{
color : string;
constructor(obj){
this.color = obj.color;
}
isColorRed(){
return color === 'red' ? true : false;
}
}
I am getting an array of Car
s from backend and want to store only ones that are red in color:
...
carsThatAreRed : Car[];
...
this.httpClient.get<Car[]>(carsUrl).pipe(
map(cars => cars.filter(car => car.isColorRed()))
).subscribe(
{
next : (carsThatAreRed) => {
this.carsThatAreRed = carsThatAreRed;
}
}
)
And this request fails and writes to dev console that
isColorRed()
is not a function
When I explicitly instantiate Car
objects from each Car
in the received array it works.
...
.pipe(
map(cars => cars.map(car => new Car(car)).filter(car => car.isColorRed()))
)
...
Why doesn't it work without explicit mapping?
CodePudding user response:
It's a runtime error. You told TypeScript that its Cars you are getting, but at the runtime it's just plain JSON objects, with no isColorRed
method on them, unless you explicitly convert them to Cars. Sth along these lines
this.httpClient.get<Vehicle[]>(carsUrl)
.pipe(
map((vehicles) => vehicles.map(vehicle => new Car(vehicle))), // now we made Cars
map(cars => cars.filter(car => car.isColorRed()))