TypeScript类型守护

297 阅读1分钟

首先呢,先了解一下,什么叫做类型守护。在特定的区块中保证某个变量属于某种确定的类型,这样你就可以放心地使用这个变量了。可以大大的提升你的代码的健壮性。

看下面这段代码:

// 普通女该
interface Girl {
    isMine: boolean;
    //isMine为false时  表示这是Girl
    say: () => {};
}

//女朋友
interface GirlFriend {
    isMine: boolean;
    //isMine为true时 表示这是GirlFriend
    sayLove: () => {};
}

//自定义方式
function judgeWho(who: Girl | GirlFriend) {
    if (who.isMine) {
        //as 断言
        (who as GirlFriend).sayLove()
    } else {
        (who as Girl).say()
    }
}

//用in的方式
function judgeWho2(who: Girl | GirlFriend) {
    //in
    if ('sayLove' in who) {
        //女友
        who.sayLove()
    } else {
        who.say()
    }
}

//用typeof 的方式 
function add(a: string | number, b: string | number) {
    if (typeof a === 'string' || typeof b === 'string') {
        return `${a}${b}`
    }
    return a + b
}


//用instanceof方式
class NumObj{
    count: number = 1024
}

function addNum(a: object | NumObj,b: object | NumObj){
    if(a instanceof NumObj && b instanceof NumObj){
        return a.count + b.count
    }
    return 0 
}