TypeScript 教程
/ 聯(lián)合類型
聯(lián)合類型
Union | (OR)
使用 |
表示我們的參數(shù)是 string
或 number
:
實(shí)例
function printStatusCode(code: string | number) { console.log(`My status code is ${code}.`) } printStatusCode(404); printStatusCode('404');
聯(lián)合類型錯(cuò)誤
注意:當(dāng)使用聯(lián)合類型時(shí),您需要知道您的類型是什么,以避免類型錯(cuò)誤:
實(shí)例
function printStatusCode(code: string | number) { console.log(`My status code is ${code.toUpperCase()}.`) // 錯(cuò)誤:屬性“toUpperCase”在“string | number”類型上不存在。 // 錯(cuò)誤:屬性“toUpperCase”在“number”類型上不存在 }
在我們的例子中,我們調(diào)用 toUpperCase() 時(shí)遇到問(wèn)題,因?yàn)樗亲址椒?,而?shù)字無(wú)法訪問(wèn)它。