如何理解 TypeScript 接口中的语法 [key: string]

Soc*_*tes 12 typescript

我无法破译我在此处的接口声明中找到的 TypeScript 语法。

interface FormattingOptions {
    tabSize: number;
    insertSpaces: boolean;
    [key: string]: boolean | number | string;
}
Run Code Online (Sandbox Code Playgroud)

有人能解释一下这个接口的第三个参数吗?一个包含[key: string] ...?这种类型的语法是如何命名的?

Tit*_*mir 15

这是一个索引签名。这意味着除了接口的已知属性之外,任何其他类型的属性booleannumber或者string可以存在

interface FormattingOptions {
    tabSize: number;
    insertSpaces: boolean;
    [key: string]: boolean | number | string;
}

let f: FormattingOptions = {
  tabSize: 1,
  insertSpaces: true,
  other: '' // witout the  index signature this would be invalid.
}; 
Run Code Online (Sandbox Code Playgroud)

  • @Socrates 是的,只要额外的属性是 boolean、number 或 string 类型。 (2认同)