在 TypeScript 中公开只读集合的​​最简洁方法是什么?

Neu*_*ino 7 typescript

如何定义一个类型,该类型公开对可以由类型本身在内部操作的集合的只读访问?

我正在寻找一种具有最少样板文件的方法。

更新

感谢到目前为止的答案,但这应该能让我更清楚地了解我在寻找什么。

export class Item {
   public Prop1: number;
   public Prop2: string;
}


export class Container {

   public get Items(): ??? {
      // Return something that enables the client to access and modify individual items but _not_ change the contents
      // of the _items array, ideally without just copying the entire array.
   }

   private _items: Item[] = [];
}
Run Code Online (Sandbox Code Playgroud)

Pal*_*leo 0

TypeScript 无法阻止开发人员更新对象的属性。

JavaScript 方式

也许使用ES6 可迭代.

或者使用ES5 getters 的实现。

...或者也许可以使用像Immutable.js这样的库?

TypeScript 的贡献

可以借助修饰符来描述readonly类型