类型保护

自定义类型保护,文档中说:一旦检查过类型,就能在之后的每个分支里清楚地知道 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