【问题标题】:How to understand syntax in TypeScript interface [key: string]如何理解 TypeScript 界面中的语法 [key: string]
【发布时间】:2018-06-01 20:05:55
【问题描述】:

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

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

谁能解释一下这个接口的第三个参数?包含[key: string] ...的那个?这种语法怎么称呼?

【问题讨论】:

标签: typescript


【解决方案1】:

这是一个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.
}; 

【讨论】:

  • 这是否意味着我可以添加任意数量的新属性?我是否还可以添加 mouse: 'tippy'car: 'BMW' 并且在此示例中仍然使变量 f 有效?
  • @Socrates 是的,只要额外的属性是布尔、数字或字符串类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
  • 2017-10-12
  • 2020-09-01
相关资源
最近更新 更多