简体   繁体   中英

Typescript not casting properly

I have a problem when casting the object. I need this object I cast to be recognized by instanceof, but for some reason this does not work. Is there some king of workaround how to exactly do that?

I made the summary of the problem here: https://stackblitz.com/edit/angular-qkdvk2

var customerJson: string = JSON.stringify(this.cus);
this.cus2 = JSON.parse(customerJson) as Customer;

if(this.cus2 instanceof Customer) // this is where this fails me, and I expect it to enter this if clause

Well the 'instanceof' operator is not working because it compares the prototype of the object that are passing through so...

When you do:

var customerJson: string = JSON.stringify(this.cus);
this.cus2 = JSON.parse(customerJson) as Customer;

if(this.cus2 instanceof Customer)

Youre just casting the value returned from the JSON.parse as a Customer but that object is not an instance of the Customer class.

To solve this you have to create an instance of the Customer class and compare that instance with the 'instanceof' operator.

var customerJson: string = JSON.stringify(this.cus);
this.cus2 = Object.assing(new Customer(), JSON.parse(customerJson));  

if(this.cus2 instanceof Customer) // This will be true

This example will create an instance of Customer and assign all properties from the parsed object.

You're just inferring the type, so you need to instantiate the class, I recommend you using the constructor, but if you need something more dynamic you can assing the parsed string to a object, like this:

var customerJson: string = JSON.stringify(this.cus);
this.cus2 = Object.assign(new Customer(), JSON.parse(customerJson));

if(this.cus2 instanceof Customer)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM