angular - 打字稿没有正确投射
问题描述
我在投射对象时遇到问题。我需要我投射的这个对象被 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
解决方案
好吧,“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 的实例并分配解析对象的所有属性。
推荐阅读
- flutter - Flutter:如何让 PageView 在某个点停止(用作抽屉)?
- qt - qmake 已安装但未找到
- python - google ai 平台上的超参数调优错误:“replica master 0 exited with a non-zero status of 1”
- python - Python字符串函数rstrip()不起作用
- flutter - 文档路径必须是非空字符串“package:cloud_firestore/src/collection_reference.dart”
- vue.js - 如何在 Vue.js 中获取用户内网 ip?
- android - 带有 RxJava Single 的 Android Livedata 在房间数据库中不起作用
- c# - 如何使用异步方法转换同步方法?
- json - 如何获得类似于 VS 代码的 VS Code Insiders 设置?
- python - 构建用于多类图像分类的 ANN 模型