自定义守卫格式
形参 is A类型:形参缩小为 A类型 返回 true
function 函数名(形参: 参数类型【参数类型大多为any】) : 形参 is A类型 {
return true or false;
}
function cal(num: string | number) {
if (isNum(num)) {
num += 10
}
}
function isNum(num: any): num is number {
return typeof num === 'number';
}
class Customer {
pay(payMethod: BankPay | MobilePay) {
if (isMobile(payMethod)) {
}
}
}
function isMobile(payMethod: BankPay | MobilePay): payMethod is MobilePay {
return payMethod instanceof MobilePay;
}