我有一些大对象,比如
const a={
b:33,
c:[78, 99],
d:{e:{f:{g:true, h:{boom:'selecta'}}}};/// well, even deeper than this...
我希望 TS 不允许我这样做
a.d.e.f.h.boom='respek';
如何完全改变对象?是否仅通过为每个深度嵌套对象创建具有“只读”接口(interface)和接口(interface)?
最佳答案
我们现在有选项 as const
,这是 @phil294 提到的第一个选项(嵌套 readonly
)的语法简洁方式。
const a = {
b: 33,
c: [78, 99],
d:{e:{f:{g:true, h:{boom:'selecta'}}}}
} as const;
a.d.e.f.h.boom = 'respek'; //Cannot assign to 'boom' because it is a read-only property.ts(2540)
作为额外的好处,您可以使用此技巧将输入设置为不可变的嵌套函数:
type Immutable<T> = {
readonly [K in keyof T]: Immutable<T[K]>;
}
所以这会发生
const a = {
b: 33,
c: [78, 99],
d:{e:{f:{g:true, h:{boom:'selecta'}}}}
}
function mutateImmutable(input: Immutable<typeof a>) {
input.d.e.f.h.boom = 'respek'; //Cannot assign to 'boom' because it is a read-only property.ts(2540)
}
关于typescript - 我想要 TS 中完全不可变的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43120022/