首页 > 其他 > 详细

类型保护

时间:2020-02-01 21:45:19      阅读:85      评论:0      收藏:0      [点我收藏+]

自定义类型保护,文档中说:一旦检查过类型,就能在之后的每个分支里清楚地知道 pet的类型的话就好了,但并未说哪种分支有效

亲测:if else 、while有效,switch无效

interface Bird {
    fly();
    layEggs();
}

interface Fish {
    swim();
    layEggs();
}

function getSmallPet(): Fish | Bird {
    let p:Bird
    return p
}

let pet = getSmallPet();

//根据返回值来判断谓语是否正确,之后在分支中就无需对谓语的主进行判断(主谓宾)
function isFish(pet: Fish | Bird): pet is Fish {
    return (<Fish>pet).swim !== undefined;
}

let p1= getSmallPet()

if(isFish(p1)){
    p1.swim()
}else {
    p1.fly()
}

switch(isFish(p1)){
    case true: p1.swim(); //亲测报错
    case false: p1.fly();
}

while(isFish(p1)){
    p1.swim()
}

--------------------------------------


包括typeof类型保护(适用于简单的基本类型)

if else 、while也是有效的

function getVal(): number | string {
    return 1
}

let v = getVal();

if(typeof v== ‘number‘){
    v++
}else {
    v.split(‘,‘)
}

while(typeof v== ‘number‘){
    v++
}

备注:

技术分享图片

 

即便是在ts里typeof依旧是es的规范

类型保护

原文:https://www.cnblogs.com/yanze/p/12250116.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!