使用in来类型守卫 判断对象 调用其中的方法提示【没有调用签名】

来源:6-5 深入类型守卫和企业项目中的真实应用场景-1

媳妇的号我来学

2024-01-06

图片描述

完整代码如下

/*
 * @Author: xiaochunyuan xiaochunyuan@yntengyun.com
 * @Date: 2024-01-06 11:03:03
 */

enum PayType {
    'ALIPAY' = '支付宝支付',
    'WXPAY' = '微信支付',
    'UNIONPAY' = '银闪付'
}
class Pay {
    private price: number
    private goodsId: string
    constructor(_goodsId: string, _price: number) {
        this.goodsId = _goodsId
        this.price = _price
    }

    toPay() {
        console.info(`支付金额${this.price},商品ID${this.goodsId}`)
    }
}


class AliPay extends Pay {
    private type: PayType
    constructor(_type: PayType, _price: number, _goodsId: string) {
        super(_goodsId, _price)
        this.type = PayType.ALIPAY
    }
    toPay(): void {
        console.info(`支付类型${this.type}`)
    }
    reportAliPay(): void {
        console.info(`上报支付宝`)
    }
}

class WXPAY extends Pay {
    private type: PayType
    constructor(_type: PayType, _price: number, _goodsId: string) {
        super(_goodsId, _price)
        this.type = _type
    }
    toPay(): void {
        console.info(`支付类型${this.type}`)
    }
    reportWx(): void {
        console.info('上报微信')
    }
}

class Customer {
    private pay: Pay
    constructor(_pay: Pay) {
        this.pay = _pay
    }

    todo() {
        this.pay.toPay()
        if (this.pay instanceof AliPay) {
            this.pay.reportAliPay()
        }
        else if (this.pay instanceof WXPAY) {
            this.pay.reportWx()
        }else{
            throw new Error("支付渠道有误")
        } 
    }

    go(){
        if('reportWx' in this.pay){
            this.pay.reportWx ()
        }else if('reportAliPay' in this.pay){
            this.pay.reportAliPay ()
        }else{
            throw new Error() 
        }
        
    }
}
const
写回答

2回答

keviny79

2024-01-07

in 来查找一个对象的类型中是否存在某个属性,存在才返回 true,   pay 对象的类型是 Pay 类型中并不存在

reportWx 属性,所以找不到。

0
0

keviny79

2024-01-06

同学你把完整代码发过来

0
0

TypeScript 从入门到深度掌握,晋级TS高手

200+技术点,22 场景应用,Vue3 源码 TS 用法剖析

430 学习 · 53 问题

查看课程