First of all, let’s look at what type guards are. Make sure that a variable is of a certain type in a particular block, so that you can use it with confidence. Can greatly improve the robustness of your code.

Take a look at this code:

// Ordinary women should
interface Girl {
    isMine: boolean;
    //isMine is false to indicate that this is Girl
    say: () = > {};
}

/ / girlfriend
interface GirlFriend {
    isMine: boolean;
    // GirlFriend is GirlFriend when isMine is true
    sayLove: () = > {};
}

// Custom mode
function judgeWho(who: Girl | GirlFriend) {
    if (who.isMine) {
        / / as assertions
        (who as GirlFriend).sayLove()
    } else {
        (who as Girl).say()
    }
}

// Use in
function judgeWho2(who: Girl | GirlFriend) {
    //in
    if ('sayLove' in who) {
        / / girlfriend
        who.sayLove()
    } else {
        who.say()
    }
}

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


// Use the instanceof method
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 
}
Copy the code