問題
我在解析在接口聲明中找到的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