简体   繁体   English

TypeScript 类中缺少方法

[英]Missing methods in TypeScript class

I have a TypeScript model which contains properties and functions like:我有一个 TypeScript 模型,其中包含以下属性和函数:

class Person {
name: string
sayHello(){ console.log(name); }
}

When creating its instance I can make use of this sayHello() method as expected.创建它的实例时,我可以按预期使用这个sayHello()方法。

The problem comes when I store and get the object from the local storage or an external web service.当我从本地存储或外部 Web 服务存储和获取对象时,问题就出现了。 While the properties are still present the methods have disappeared.虽然属性仍然存在,但方法已经消失了。 (obviously because it's just text). (显然是因为它只是文本)。

Is there any way to restore the completeness of the object to be able to use its functions?有什么方法可以恢复对象的完整性以能够使用其功能吗?

Or otherwise, is there any other technique?否则,还有其他技术吗? For instance, helper class that can work with type.例如,可以使用类型的助手类。

When you save to a local storage, you will save a JSON representation of the class data;当您保存到本地存储时,您将保存类数据的 JSON 表示; when you get the object back from the local storage, it will be just an object, not an instance of the original class.当您从本地存储取回对象时,它将只是一个对象,而不是原始类的实例。

You can look for an external library that will help you with this, but the simple solution is to create a new instance of the class and assign the field values to the class using Object.assign :您可以寻找可以帮助您解决此问题的外部库,但简单的解决方案是创建类的新实例并使用Object.assign将字段值分配给类:

class Person {
    public constructor(public name?: string){}
    sayHello() { console.log(name); }
}
let p = new Person("Test");
let data = JSON.stringify(p);
let p2 = new Person()
Object.assign(p2, JSON.parse(data));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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