[Typescript] Dealing with union types

type Twitter = { tweets: number}
type Instagram = {canFollow: boolean}

function describeAccount(account: Twitter | Instagram) {
    if (account.tweets) {
        // this ill give a compile-time error
    }
}

// Now typescript knows- andwe can access the "tweets" property.
function describeAccount(accont: Twitter | Instagram) {
    if ( "tweets" in account) {
        console.log('Has tweets:', account.tweets);
    }
}

 

posted @ 2022-03-30 15:26  Zhentiw  阅读(38)  评论(0编辑  收藏  举报