简体   繁体   English

TypeScript,带有 getter 和 json 的私有属性

[英]TypeScript, private properties with getters and json

I'm pretty new to JavaScript/Typescript overall and I've run into an issue with serialization of classes that I don't know how to handle.总的来说,我对 JavaScript/Typescript 还是很陌生,我遇到了一个我不知道如何处理的类序列化问题。

I create objects from REST or database requests requests like this:我从 REST 或数据库请求请求创建对象,如下所示:

export interface ILockerModel {
    id: string
    lockerId: string
    ownerId: string
    modules: IModuleModel[]
}
export class LockerModel implements ILockerModel {
    private _id: string
    private _lockerId: string
    private _ownerId: string
    private _modules: ModuleModel[]

    constructor(document: ILockerModel) {
        this._id = document.id
        this._lockerId = document.lockerId
        this._ownerId = document.ownerId
        this._modules = document.modules.map(m => new ModuleModel(m))
    }
    // Utility methods
}

I then have multiple utility methods that make it easier to work with the model, adding and removing things from lists and so on.然后我有多种实用方法,可以更轻松地使用模型,从列表中添加和删除内容等等。

When I'm done I want to persist the object to a document database or return it in a REST response, so I call JSON.stringify(objectInstance) .完成后,我想将对象持久保存到文档数据库或在 REST 响应中返回它,因此我调用JSON.stringify(objectInstance) However, this gives me the class but with all properties underscored ( _ ), not my getter values.但是,这为我提供了类,但所有属性都带有下划线 ( _ ),而不是我的 getter 值。 This breaks the deserializtion in other parts of my application.这打破了我应用程序其他部分的反序列化。

Serializing the interface gives me what I want, but I haven't found a straightforward way to go from the class to the interface representation.序列化接口给了我我想要的东西,但我还没有找到从类到接口表示的直接方法。 The issue gets tougher because I deserialize the data in a hierarchy (see the modules mapping in the constructor).这个问题变得更加棘手,因为我反序列化了层次结构中的数据(请参阅构造函数中的模块映射)。

How do you usually solve this issue?你通常如何解决这个问题?

As far as I can see you do not really implement the ILockerModel .据我所知,您并没有真正实现ILockerModel Shouldnt this throw an error?这不应该抛出错误吗?

When I run it, I get the following:当我运行它时,我得到以下信息:

Type 'LockerModel' is missing the following properties from type 'ILockerModel': id, lockerId, ownerId, modules “LockerModel”类型缺少“ILockerModel”类型中的以下属性:id、lockerId、ownerId、modules

The other thing is that JSON.strigify() just takes your object and makes a string representation of all its properties.另一件事是JSON.strigify()只是获取您的对象并对其所有属性进行字符串表示。 It does not care about your getters.它不关心你的吸气剂。 If you want it to transform it to the right format, you should give it an object in the correct format.如果你想让它把它转换成正确的格式,你应该给它一个正确格式的对象。

One solution would be to just remove the '_' from all the keys, by using a combination of map and reduce :一种解决方案是通过使用mapreduce的组合从所有键中删除“_”:

 const input = { _test: 123, _hello: 'world' }; console.log(input); console.log(JSON.stringify(input)); const convertToJson = (obj) => { return Object.entries(obj) // Create array from object .map(([key, value]) => [ // change key to remove '_' key.startsWith('_') ? key.substring(1) : key, value ]) .reduce((acc, [key, value]) => { // Transform back to object acc[key] = value; return acc; }, {}); } const output = convertToJson(input); console.log(output); console.log(JSON.stringify(output));

Or if you are allowed to use ES10:或者,如果您被允许使用 ES10:

 const input = { _test: 123, _hello: 'world' }; console.log(input); console.log(JSON.stringify(input)); const convertToJson = (obj) => { return Object.fromEntries( // Create Object from array Object.entries(obj) // Create array from object .map(([key, value]) => [ // change key to remove '_' key.startsWith('_') ? key.substring(1) : key, value ]) ); } const output = convertToJson(input); console.log(output); console.log(JSON.stringify(output));

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

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