0

hi i have the following models:

export class Vehicle {
}

export class Trike extends Vehicle {
}

export class Car extends Vehicle {
}

These are retrieve from a Mock of an API

 var vehiclesResource = vehicleService.getResource();
        vehiclesResource.query((data) => {
            this.areas = data;

            var c = data[0] instanceof Car;
            var t = data[0] instanceof Trike;

            var cc = data[0].constructor === Car;
            var tt = data[0].constructor === Trike;
        });

A car is retrieved from the API, now when the data arrives i want to cast it to the correct object (Car in this case). but some how c = false t = false cc = false and tt = false.

setting the breakpoint in visualstudio shows me the data is of the type Object (Resource)

what am i doing wrong?

Raymond
  • 93
  • 7

1 Answers1

0

Most likely is that you are receiving data by means of deserializing it. In this case the type of the object will be lost even though its structure will be the same. For example if you do the following:

let a = new Car();
let data = JSON.stringify();
let aa = JSON.parse(data);

The type of the 'aa' object will be 'Object' and not 'Car'. If it is acceptable you can convert you class definitions to interface definitions instead and use it like this:

let aa = <Car>JSON.parse(data);

Or you can implement your own deserialization method, more info here: How do I initialize a typescript object with a JSON object

Community
  • 1
  • 1
Amid
  • 21,508
  • 5
  • 57
  • 54
  • Ok lets say i create an interface IVehicle and then do a request on my api. the api can return me a Trike or a Car but i dont know which it is on the receiving end. How do i get the correct object type from the data since the data can be an array of IVehicle which can be either a Car or a Trike. – Raymond Jan 27 '16 at 15:11
  • Yes it is so. In that case you must go with the second approach I referred to. – Amid Jan 27 '16 at 15:12
  • Ok i see i will need to read this more carefully. Unfortunately it looks like you need to add a property "name" or such to the object for that to work. i was hoping there was something like a dynamic_cast or so which you could use in c++. – Raymond Jan 27 '16 at 15:18