日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

什么是TypeScript的字符串索引签名

發布時間:2023/12/19 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 什么是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的字符串索引签名的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。