typeScript学习
自定义守卫
function 函数名(形参:参数类型【参数类型大多数为any】): 形参 is A 类型{
return true or false
}
class Customer {
pay(payMethod: BankPay | MobilePay) {
if (isMobilePay(payMethod)) {
payMethod // MobilePay
}
}
}
// 自定义守卫
function isMobilePay(payMethod: any): payMethod is MobilePay {
return payMethod instanceof MobilePay
}
function cal(num: string | number) {
// num = num + 10 // 错误
if (isNum(num)) {
num + 3
} else {
num + 10
}
}
function isNum(num: any): num is number {
return typeof num === 'number'
}
export { }