gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:11:16 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com