TypeScript 之 深入类型守卫

86 阅读2分钟

为什么要用类型守卫

类型守卫定义:在 语句的块级作用域【if 语句内或条目运算符表达式内】缩小变量的一种类型推断行为。

类型守卫产生时机:TS 条件语句中遇到下列条件关键字时,会在语句内的块级作用域内缩小变量的类型,这种类型推断的行为称作类型守卫(Type Guard)。类型守卫可以帮助我们在块级作用域中获得更为需要的精确变量类型。

  • 实例判断:instanceof
  • 属性或者方法判断:in
  • 类型判断:typeof
  • 字面量相等判断:==, ===, !=, !==

instanceof 判断构造函数是否属于参数的原型链上


class Pay {
  constructor(bank_card_no: string, balance: number, cost: number, tokenid: string) {
    this.bank_card_no = bank_card_no;
    this.balance = balance;
    this.cost = cost;
    this.tokenid = tokenid;
  }
  bank_card_no: string
  balance: number
  cost: number
  tokenid: string
  pay() {
    console.log('支付银行卡卡号', this.bank_card_no);
  }
}


class BankPay extends Pay {
  bank_network!: string // 银行网点
  bankno_type!: number // 银行卡类型
  bank_card_psw!: string // 银行卡密码
  custname!: string // 顾客姓名
}

class MobilePay extends Pay {
  constructor(bank_card_no: string, balance: number, cost: number, tokenid: string, type: PayType, change: number, opendid: string, appid: string) {
    super(bank_card_no, balance, cost, tokenid)
    this.type = type;
    this.change = change;
    this.opendid = opendid;
    this.appid = appid;
  }
  type: PayType
  change: number
  opendid: string
  appid: string
  pay() {
    super.pay();
    console.log('完成支付。。。。');
  }
}

class Customer {
  pay(payMethod: BankPay | MobilePay) {

    if (payMethod instanceof BankPay) {
      // payMethod.
    } else if (payMethod instanceof MobilePay) {

    }
  }
}

let webChatPay = new MobilePay('111', 300, 100, '1awdfas', PayType.WebChat, 10, '111asfg', 'asdfasdfda');

let cust = new Customer();
cust.pay(webChatPay)

属性或者方法判断 in


class Pay {
  constructor(bank_card_no: string, balance: number, cost: number, tokenid: string) {}
  bank_card_no: string
  balance: number
  cost: number
  tokenid: string
  pay() {
    console.log('支付银行卡卡号', this.bank_card_no);
  }
}


class BankPay extends Pay {
  bank_network!: string // 银行网点
  bankno_type!: number // 银行卡类型
  bank_card_psw!: string // 银行卡密码
  custname!: string // 顾客姓名
}

class MobilePay extends Pay {
  constructor(bank_card_no: string, balance: number, cost: number, tokenid: string, type: PayType, change: number, opendid: string, appid: string) {
    super(bank_card_no, balance, cost, tokenid)
    this.type = type;
    this.change = change;
    this.opendid = opendid;
    this.appid = appid;
  }
  type: PayType
  change: number
  opendid: string
  appid: string
  pay() {
    super.pay();
    console.log('完成支付。。。。');
  }
   xx() { }
}

class Customer {
  pay(payMethod: BankPay | MobilePay) {
   if ('xx' in payMethod) {
      payMethod // 缩小为MobilePay类型
    }
  }
}

let webChatPay = new MobilePay('111', 300, 100, '1awdfas', PayType.WebChat, 10, '111asfg', 'asdfasdfda');

let cust = new Customer();
cust.pay(webChatPay)