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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM