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

时间:2018-06-01 20:05:56

标签: typescript

我在解密我在此处的接口声明中找到的TypeScript语法时遇到了问题。

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

有人能解释一下这个界面的第三个参数吗?包含[key: string] ...的那个?这种语法是如何调用的?

1 个答案:

答案 0 :(得分:2)

它是index signature。这意味着除了接口的已知属性之外,还可以存在booleannumberstring类型的任何其他属性

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.
};