投射对象时出现问题。我需要我强制转换的该对象以被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
答案 0 :(得分:3)
'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实例,并分配解析对象的所有属性。
答案 1 :(得分:2)
您只是在推断类型,因此您需要实例化该类,我建议您使用构造函数,但是如果您需要更多动态的东西,则可以将解析的字符串赋给一个对象,如下所示:
var customerJson: string = JSON.stringify(this.cus);
this.cus2 = Object.assign(new Customer(), JSON.parse(customerJson));
if(this.cus2 instanceof Customer)