什么是TypeScript的字符串索引签名
可選屬性
interface SquareConfig {color?: string;width?: number; }function createSquare(config: SquareConfig): {color: string; area: number} {let newSquare = {color: "white", area: 100};if (config.color) {newSquare.color = config.color;}if (config.width) {newSquare.area = config.width * config.width;}return newSquare; }let mySquare = createSquare({color: "black"});可選屬性的優點在于,可以捕獲引用了不存在的屬性時的錯誤。 比如,我們故意將 createSquare里的color屬性名拼錯,就會得到上圖的錯誤提示。
如果消費這個函數時傳入的對象字面量參數也不包含color屬性:
同樣會報錯:
即使使用類型斷言也不行:
錯誤消息:
Conversion of type ‘{ colour: string; width: number; }’ to type ‘SquareConfig’ may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to ‘unknown’ first.
Property ‘color’ is missing in type ‘{ colour: string; width: number; }’ but required in type ‘SquareConfig’.
17 let mySquare = createSquare({ colour: “red”, width: 100 } as SquareConfig);
解決辦法是使用字符串索引簽名,并且將color屬性加上問號修飾,使其變成optional:
第四行[propName:string]:any的含義是,SquareConfig可以有任意數量的屬性,并且只要它們不是color和width,那么就無所謂它們的類型是什么。
要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":
總結
以上是生活随笔為你收集整理的什么是TypeScript的字符串索引签名的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TypeScript的类型断言,有点像A
- 下一篇: 【转】利用syslinux制作Dos、W