sha*_*hal 7 typescript typescript2.0
我有一些大物件,例如
const a={
b:33,
c:[78, 99],
d:{e:{f:{g:true, h:{boom:'selecta'}}}};/// well, even deeper than this...
Run Code Online (Sandbox Code Playgroud)
而且我希望TS 不要让我做
a.d.e.f.h.boom='respek';
Run Code Online (Sandbox Code Playgroud)
我怎样才能完全改变物体?是否仅通过为每个深度嵌套对象创建带有“只读”的接口和接口?
Aja*_*ung 21
我们现在有一个选项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)
Run Code Online (Sandbox Code Playgroud)
作为额外的好处,您可以使用以下技巧为嵌套的不可变函数输入:
type Immutable<T> = {
readonly [K in keyof T]: Immutable<T[K]>;
}
Run Code Online (Sandbox Code Playgroud)
所以这会发生
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)
}
Run Code Online (Sandbox Code Playgroud)
如https://www.typescriptlang.org/docs/handbook/interfaces.html 中所述,您可以readonly在类/接口属性或Readonly<...>/ReadonlyArray<>用于不可变对象和数组。在您的情况下,这将如下所示:
const a: Readonly<{
b: number,
c: ReadonlyArray<number>,
d: Readonly<{
e: Readonly<{
f: Readonly<{
g: boolean,
h: Readonly<{
boom: string
}>
}>
}>
}>
}> = {
b: 33,
c: [78, 99],
d:{e:{f:{g:true, h:{boom:'selecta'}}}}
}
a.d.e.f.h.boom = 'respek'; // error: Cannot assign to 'boom' because it is a constant or a read-only property.
Run Code Online (Sandbox Code Playgroud)
显然,这是同义反复的陈述,所以我建议你为你的对象定义适当的类结构。仅仅通过声明一个嵌套的、无类型的对象,你并没有真正利用 Typescript 的任何功能。
但是如果你真的需要没有类型定义,我认为唯一的方法是像 Hampus 建议的那样定义一个冰柜(喜欢这个词:D)。来自deepFreeze(obj)功能从MDN:
function freezer(obj) {
Object.getOwnPropertyNames(obj).forEach(name => {
if (typeof obj[name] == 'object' && obj[name] !== null)
freezer(obj[name]);
});
return Object.freeze(obj);
}
const a = freezer({
b:33,
c:[78, 99],
d:{e:{f:{g:true, h:{boom:'selecta'}}}}});
a.d.e.f.h.boom='respek'; // this does NOT throw an error. it simply does not override the value.
Run Code Online (Sandbox Code Playgroud)
tl;dr:如果没有定义类型,你就不会得到编译器类型错误。这就是 Typescript 的全部意义所在。
编辑:
最后这句话是错误的。例如,
let a = 1
a = "hello"
Run Code Online (Sandbox Code Playgroud)
会抛出错误,因为类型被隐式设置为数字。但是,对于只读,我认为,您将需要如上定义的正确声明。
Minko Gechev创建了 DeepReadonly 类型:
type DeepReadonly<T> =
T extends (infer R)[] ? DeepReadonlyArray<R> :
T extends Function ? T :
T extends object ? DeepReadonlyObject<T> :
T;
interface DeepReadonlyArray<T> extends ReadonlyArray<DeepReadonly<T>> {}
type DeepReadonlyObject<T> = {
readonly [P in keyof T]: DeepReadonly<T[P]>;
};
interface Person {
name: string;
job: { company: string, position:string };
}
const person: DeepReadonly<Person> = {
name: 'Minko',
job: {
company: 'Google',
position: 'Software engineer'
}
};
person.job.company = 'Alphabet'; // Error
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4250 次 |
| 最近记录: |