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