TypeScript真值縮小
function getUserOnlineMessage(numUserOnline: number): string {
if (numUserOnline) {
return `現(xiàn)在共有 ${numUserOnline} 人在線`;
} else {
return "現(xiàn)在沒人在線."
}
}
此處使用了強制類型轉(zhuǎn)換煌抒。
除了以下幾個裁赠,強制類型轉(zhuǎn)換均為True:
- 0
- NaN
- "" (空字符串)
- On (bigint零的版本)
- null
- undefined
另外轉(zhuǎn)換類型的方法:
Boolean("hello"); // type: boolean, value: true
!!"world"; // type: bllean, value: true
可以防范null和undefined問題脐瑰。
function printAll(strs: string | string[] | null): void {
if (strs && typeof strs === "object") {
for (const s of strs) {
// ...
}
} else if (typeof strs === "string") {
// ...
} else {
// ...
}
}