手册目录
使用 | 表示我们的参数是 string 或 number:
function printStatusCode(code: string | number) {
console.log(`My status code is ${code}.`)
}
printStatusCode(404);
printStatusCode('404');
注意:当使用联合类型时,您需要知道您的类型是什么,以避免类型错误:
function printStatusCode(code: string | number) {
console.log(`My status code is ${code.toUpperCase()}.`) // 错误:属性“toUpperCase”在“string | number”类型上不存在。
// 错误:属性“toUpperCase”在“number”类型上不存在
}
在我们的例子中,我们调用 toUpperCase() 时遇到问题,因为它是字符串方法,而数字无法访问它。
科技资讯
24小时阅读榜
1
2
3
4
5
6
7
8
9
10
精品课程
共5课时 | 18.1万人学习
共49课时 | 82.8万人学习
共29课时 | 65.3万人学习
共25课时 | 41.5万人学习
共43课时 | 77.2万人学习