我想定義一個類,該類將物件陣列作為其建構式引數之一,并且我想保證陣列和其中的物件都不會被修改。我目前的嘗試使用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)。
經過一番搜索,我發現了一個情侶的答案這似乎,如果我正確地理解他們,以表明可變陣列和readonly/Readonly<T>陣列不能被分配給彼此。
那么,我怎樣才能代表我試圖表達的不變性契約呢?我正在使用 Typescript 4.5.2,我tsconfig.json的如下:
{
"compilerOptions": {
"exactOptionalPropertyTypes": true,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noUncheckedIndexedAccess": true,
"strict": true
}
}
uj5u.com熱心網友回復:
我會使用一個ReadonlyArray.
export type Foo = { foo: string };
export class Bar {
readonly foo: Foo;
readonly bars: ReadonlyArray<Readonly<Bar>>;
constructor(
foo: Readonly<Foo>,
bars: ReadonlyArray<Readonly<Bar>>,
) {
this.foo = foo;
this.bars = bars;
}
}
在陳述句中readonly bars: ReadonlyArray<Readonly<Bar>>,不同部分的含義如下:
readonly宣告該bars屬性是只讀的,它會阻止您寫入this.bars = whatever.ReadonlyArray宣告該陣列是只讀的,它會阻止您寫入this.bars[0] = whatever.Readonly<Bar>宣告陣列的元素是只讀的,它可以防止this.bars[0].foo = whatever.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/366069.html
標籤:打字稿
下一篇:基于函式數量的型別保護
