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

时间:2020-08-25 12:58:01

标签: javascript json typescript

总体来说,我对JavaScript / Typescript还是很陌生,我遇到了一个我不知道如何处理的类的序列化问题。

我通过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
}

然后,我有了多种实用程序方法,这些方法可以更轻松地使用模型,在列表中添加和删除内容等。

完成后,我想将该对象持久保存到文档数据库中或以REST响应形式返回它,所以我叫JSON.stringify(objectInstance)。但是,这给了我类,但所有属性都带有下划线(_),而不是我的getter值。这破坏了我应用程序其他部分的反序列化。

序列化接口给了我想要的东西,但是我还没有找到一种从类到接口表示的直接方法。这个问题变得更加棘手,因为我在层次结构中反序列化了数据(请参阅构造函数中的模块映射)。

您通常如何解决此问题?

1 个答案:

答案 0 :(得分:1)

据我所知,您并没有真正实现ILockerModel。这不应该引发错误吗?

运行它时,我得到以下信息:

类型'LockerModel'缺少类型'ILockerModel'中的以下属性:id,lockerId,ownerId,模块

另一件事是JSON.strigify()只是获取您的对象并对其所有属性进行字符串表示。它不在乎您的吸气剂。如果希望将其转换为正确的格式,则应为其提供正确格式的对象。

一种解决方案是仅使用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));

或者如果允许您使用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));

相关问题