任何形状行为的Typescript 2冻结对象

Typescript 2 frozen object of any shape behavior

假设我处理了一些对象,其内部结构未知,因为我没有创建它。例如,我得到了包含 html 属性的对象 attributes 的引用,然后我做了浅拷贝并用 Object.freeze({...attributes}).

冻结了它

我试着描述形状

interface HTMLAttributes = Readonly<{
  [attribute: string]: string
}>

or like

interface HTMLAttributes = {
  readonly [attribute: string]: string
}

但我在直接赋值时仍然无法达到预期的错误attributes.class = '<stuff>'

attributes['class'] = '<stuff>' 的赋值按预期抛出。

示例 (view it on the TypeScript Playground):

interface Example {
  readonly [attribute: string]: string
}

var x: Example = {};

x['test'] = 'foo'; // Error: Permits only reading

x.test = 'foo'; // No Error

打字稿的以下部分描述了原因 specs

Index signatures affect the determination of the type that results from applying a bracket notation property access to an instance of the containing type, as described in section 4.13.

换句话说,只有在使用括号表示法时才会应用您的限制。