我想定义一个类,它将一个对象数组作为其构造函数参数之一,并保证数组和其中的对象都不会被修改。我当前的尝试使用
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;
}
}
(
Playground link.
)
然而,这在线路上产生了一个错误
this.bars = bars;
说
The type 'readonly Readonly<Bar>[]' is 'readonly' and cannot be assigned to the mutable type 'Readonly<Bar>[]'.ts(4104)
.
经过一番搜索,我发现了
couple
属于
answers
如果我正确理解的话,这似乎表明可变数组和
只读的
/
只读<T>
数组不能相互分配。
那么,我如何才能代表我试图表达的不变性契约呢?我使用的是打字4.5.2和我的
tsconfig.json
如下所示:
{
"compilerOptions": {
"exactOptionalPropertyTypes": true,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noUncheckedIndexedAccess": true,
"strict": true
}
}