我有一个第三方类对象,我想将该对象的属性设置为只读。所以我不能用 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/