首页 > 解决方案 > How to understand syntax in TypeScript interface [key: string]

问题描述

I'm having trouble deciphering a TypeScript syntax I found within an interface declaration here.

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

Can someone explain me the third parameter of this interface? The one containing [key: string] ...? How is this type of syntax called?

标签: typescript

解决方案


这是一个索引签名。这意味着除了接口的已知属性之外,任何其他类型的属性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.
}; 

推荐阅读