好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

我在解析在接口声明中找到的TypeScript语法时遇到了麻烦。

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

有人可以解释一下该接口的第三个参数吗?这个[key: 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.
}; 
 

See

https://basarat.gitbook.io/typescript/type-system/index-signatures

查看更多关于如何理解TypeScript接口​​中的语法[key: string]以及[key: number]的详细内容...

  阅读:51次