javascript - ReactJs/ typescript : Make component state object and properties readonly

标签 javascript reactjs typescript

我有一个第三方类对象,我想将该对象的属性设置为只读。所以我不能用 this.state.object.props = "xx";

改变状态

看起来像这样

class ThirdPartyObject {
    id?: string;
}

interface ComponentState {
    readonly object: ThirdPartyObject;
}

this.state.object = null; // not possible
this.state.object.id = "newId"; // should also not be possible

我该怎么做?

最佳答案

如果您希望 ThirdPartyObject 字段是只读的,请使用 Readonly 类型:

class ThirdPartyObject {
  id?: string;
}

interface ComponentState {
  readonly object: Readonly<ThirdPartyObject>;
}

然后这个: this.state.object.id = 'newId'; 会抛出错误。

关于javascript - ReactJs/ typescript : Make component state object and properties readonly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58729663/

相关文章:

javascript - js复制功能在html中不起作用

javascript - 捕获地理位置错误 - 异步等待

javascript - onChange 不起作用,但已记录在控制台中

javascript - 大 React 类还是外部 Controller ?

javascript - 文本行不从同一位置开始

javascript - 仅使用 JavaScript 选择 NAV 元素时如何更改其样式?

javascript - 从请求中分派(dispatch) redux 操作的正确方法

interface - 如何导出已导入的接口(interface)?

javascript - 如何防止可观察的发射值发生突变

javascript - 在 Angular2 中,你如何根据事件路线更改侧边栏?