Gavin Yap
Gavin Yap

Reputation: 762

Typecast an Object to another class in Typescript

I've a class of FooError

class FooError{
    code: number;
    message: string;
    data: Object;
}

In Angular2, I've do a http post in a Service as follows:

export class FooService{
    ...some other code...
    get(){

    this._http.post(url, data, options)
        .map(res => res.json())
        .map(data => {
            if(data.error){
                throw data.error
            }
            return data.result
        })
        ....

Now, since any Type of Errors can be thrown when subscribe to this post Observable.

E.g.

Response(error object class type) will be return if a) server's dead, b) backend behind proxy is dead c)etc.

How can I cast "data.error" to FoorError class so I can differentiate the errors that I would received after call.

What I had tried and doesn't work

let error:FooError = <FooError> data.error;
throw error;

I've also tried Javascript way, which also does work

Object.create(FooError, data.error)

Upvotes: 1

Views: 3674

Answers (1)

Amid
Amid

Reputation: 22322

http request returns plain JSON objects without any type information attached. The fact that you cast it to allows only compile time checks to be run smoothly but does not change the actual type of the object that is still Object.

So if you want to have actual instance of the OdooError - you will have to construct it manually from the received JSON object. Naitive javascript JSON deserialization unfortunately does not provide this possibility.

Here are some more info on the subject: link

And my personal attempt on the same matter: github

Upvotes: 4

Related Questions