J.F.Dimdim
J.F.Dimdim

Reputation: 47

Unable to call functions on observable results

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 Cars 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?

Upvotes: 1

Views: 47

Answers (2)

Saptarsi
Saptarsi

Reputation: 888

What we do in typescript using as or <> is called Type assertions.

  • Type assertions will not covert plain javascript object into custom type object.

  • Type assertions are hint to compiler / IDE

  • Type assertions are a way to tell the compiler “trust me, I know what I’m doing.”

  • Type assertions has no runtime impact and is used purely by the compiler.

Take a look at the compiled JavaScript and you will see the type assertion (casting) disappears because it's only for compiling

That's why IDE / Compiler is able to show suggestion isColorRed after car.

isColorRed is not available in response [{plain javascript object}]

So in-order to use isColorRed metod against car object,you need to instantiate Car object using javascript objet value.

this.httpClient
  .get<Car[]>(carsUrl)
  .pipe(map((cars) => cars.filter((car: Car) => new Car(car).isColorRed())))
  .subscribe({
    next: (carsThatAreRed) => {
      this.carsThatAreRed = carsThatAreRed;
    },
  });

Upvotes: 1

mbojko
mbojko

Reputation: 14679

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()))

Upvotes: 3

Related Questions