如何理解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

posted @ 2021-01-15 17:21  develon  阅读(3975)  评论(1编辑  收藏  举报