TypeScript类型保护

TypeScript在使用联合类型的时候,会因为不同类型拥有不同属性或者方法在调用时出错,如下例:

interface Bird {
    fly: boolean;
    sing: () => {}
}

interface Dog {
    fly: boolean;
    bark: () => {}
}

function Animal(animal: Bird | Dog) {
    animal.sing(); // error
    animal.bark(); // error
}

上例中,Bird 和 Dog都有 fly 属性,但是 Bird独有sing方法,Dog独有 bark方法,函数Animal的入参可以是Bird型也可以是Dog型,但在函数内部调用 sing 或者 bark 时,均会报错,怎么解决这个问题呢?

常见的类型保护方式有四种:

1. 类型断言的方式

function Animal(animal: Bird | Dog) {
    if (animal.fly) {
        (animal as Bird).sing();
    } else {
        (animal as Dog).bark();
    }
}

2. in 属性判断

判断当前入参是否包含该属性

function Animal(animal: Bird | Dog) {
    if ('sing' in animal) {
        animal.sing(); 
    } else if ('bark' in animal) {
        animal.bark(); 
    }
}

3. typeof 判断

function add(first: string | number,second:string | number) {
    if (typeof first === 'string' || typeof second === 'string') {
        return `${first}${second}`
    } else {
        return first + second;
    }
}

4. instanceof 判断

class NumberObj {
    count: number
}

function addSecond(first: object | NumberObj,second: object | NumberObj) {
    if (first instanceof NumberObj && second instanceof NumberObj) {
        return first.count + second.count;
    }

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端卡卡西呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值