首页 > 解决方案 > 打字稿没有正确投射

问题描述

我在投射对象时遇到问题。我需要我投射的这个对象被 instanceof 识别,但由于某种原因,这不起作用。是否有一些解决方法之王如何做到这一点?

我在这里对问题进行了总结: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

标签: angulartypescript

解决方案


好吧,“instanceof”运算符不起作用,因为它比较了正在通过的对象的原型,所以......

当你这样做时:

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

if(this.cus2 instanceof Customer)

您只是将从 JSON.parse 返回的值转换为 Customer,但该对象不是 Customer 类的实例。

要解决这个问题,您必须创建 Customer 类的实例并将该实例与“instanceof”运算符进行比较。

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

此示例将创建 Customer 的实例并分配解析对象的所有属性。


推荐阅读