【发布时间】:2021-11-26 06:05:54
【问题描述】:
我想定义一个类,它将对象数组作为其构造函数参数之一,并且我想保证数组和其中的对象都不会被修改。我目前的尝试使用readonly 修饰符和Readonly<T> 泛型,看起来像这样:
export type Foo = { foo: string };
export class Bar {
readonly foo: Foo;
readonly bars: Array<Readonly<Bar>>;
constructor(
foo: Readonly<Foo>,
bars: Readonly<Array<Readonly<Bar>>>,
) {
this.foo = foo;
this.bars = bars;
}
}
但是,这会在this.bars = bars; 行出现错误,说The type 'readonly Readonly<Bar>[]' is 'readonly' and cannot be assigned to the mutable type 'Readonly<Bar>[]'.ts(4104)。
经过一番搜索,我找到了answers 中的couple,如果我理解正确的话,这似乎表明可变数组和readonly/Readonly<T> 数组不能相互分配。
那么,我如何表示我试图表达的不变性契约?我使用的是 Typescript 4.5.2,我的tsconfig.json 如下:
{
"compilerOptions": {
"exactOptionalPropertyTypes": true,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noUncheckedIndexedAccess": true,
"strict": true
}
}
【问题讨论】:
标签: typescript