【问题标题】:How to ignore protected readonly member of class during serialization如何在序列化期间忽略类的受保护只读成员
【发布时间】:2020-03-09 20:24:45
【问题描述】:

假设我在 Typescript 中有一个类,它有一个受保护的只读成员,它是构造函数参数,以及从该类扩展并使用该属性的多个类:

class Yolo {
    public readonly swolo: boolean = false;
    // Lots of other properties

    constructor(protected readonly swag: string = '') {}
}

我希望JSON.stringify(new Yolo()) 产生的字符串没有任何swag:

{"swolo":false, ...(Every other property except "swag")}

有没有办法通过排除(即不使用JSON.stringify 上的第二个参数),因为该类还有许多其他属性,并且仍然保留 Intellisense?

我最初的想法是将toJSON 写成类似

public toJSON() {
    const serializableEntries: {
        -readonly [K in keyof Yolo]: Yolo[K]
    } = {
        ...this
    };

    delete serializableEntries.swag;
    return serializableEntries;
}

但这会导致编译错误,因为keyof Yolo 不包含swag:

类型 '{ toJSON: () => 字符串上不存在属性 'swag'; }'。

我考虑了以下解决方法:

  1. 我可以在toJSON 中转换为any
  2. 我可以删除readonly 类声明中的修饰符并删除 toJSON 中 serializableEntries 上的类型声明
  3. 我可以公开swag

但在我看来,这些选项中没有一个是有利的。我想保持 Intellisense 和访问修饰符不变。甚至可能吗?

【问题讨论】:

  • 尽可能使用 getter。
  • 对不起,我应该在描述中澄清这一点,但这是不可能的,因为该属性实际上是动态的。我会换个问题。

标签: json typescript class encapsulation protected


【解决方案1】:

用object destructuring怎么样:

public toJSON(): string {
    const { swag: _, ...props } = this;
    return JSON.stringify(props);
}

这具有将this 的所有属性复制到props 中的效果,swag 属性除外。

console.log(new Yolo("shwag").toJSON()); //{"swolo":false}

我觉得不错。希望有帮助;祝你好运!

Link to code

【讨论】:

  • 喜欢,谢谢。我总是忘记这个功能,因为它的语法让我大吃一惊。
猜你喜欢
  • 2017-06-04
  • 1970-01-01
  • 2020-01-31
  • 1970-01-01
  • 2018-12-27
  • 2013-08-17
  • 2016-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多