gpt4 book ai didi

javascript - 尝试更新我的对象中的 bool 属性的 Typescript 收到 "TypeError: Cannot assign to read only property"

转载 作者:行者123 更新时间:2023-12-03 00:40:55 24 4
gpt4 key购买 nike

如果我有已经定义的对象,如何更改属性的值?我还有其他选择吗?

export interface myTest {
shouldChange: boolean; // <-- not using readonly
}

const testObj = {
shouldChange: false
} as myTest;

// later on
testObj.shouldChange = true // <-- this throws the following error

TypeError: Cannot assign to read only property 'shouldChange' of object '[object Object]'

最佳答案

我不确定此代码是否在 NGRX 上下文中使用,但无论如何,请考虑尝试以下操作:

testObj = {...testObj};

在 NGRX 上下文中,您从存储中获取的数据处于卡住状态并且是只读的。使用此代码(它是扩展运算符,相当于 testObj = Object.Assign({}, testObj) ),您基本上创建了一个与之前的 testObj 看起来相同的全新对象。 。唯一的区别是,该对象没有卡住状态,可以自由调整。

如果您有更深的对象并且需要调整这些对象,则必须使用 cloneDeep来自洛达什

export interface myTest {
shouldChange: boolean;
somethingElse: DeepObject;
}

export class DeepObject {
index: number;
}

testObj = _.cloneDeep(testObj);
testObj.somethingElse.index = 42; // <-- Does not throw errors

关于javascript - 尝试更新我的对象中的 bool 属性的 Typescript 收到 "TypeError: Cannot assign to read only property",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53469830/

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