代码之家  ›  专栏  ›  技术社区  ›  Ben Blank Jarret Hardie

如何表示不可变对象的不可变数组?

  •  0
  • Ben Blank Jarret Hardie  · 技术社区  · 4 年前

    我想定义一个类,它将一个对象数组作为其构造函数参数之一,并保证数组和其中的对象都不会被修改。我当前的尝试使用 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
      }
    }
    
    0 回复  |  直到 4 年前
        1
  •  4
  •   GOTO 0    4 年前

    我会用 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 .
    • 只读数组 声明数组是只读的,它会阻止您写入 this.bars[0] = whatever .
    • Readonly<Bar> 声明数组的元素是只读的,它防止 this.bars[0].foo = whatever .
    推荐文章