简体   繁体   中英

can typescript do union type assertion in this case?

can typescript do union type assertion in this case? i want to use ab.a or ab.b or ab. hasOwnProperty ab. hasOwnProperty to do assertion of type A or type B ? how do i do?

export interface A extends Object {
    a: string;
}

export interface B extends Object {
    b: number;
}

export type AorB = A | B;

function test(ab: AorB) {
    // can ts auto predict this ?
    if (ab.hasOwnProperty('a')) {
        ab.a // type error
    }
}

Update your function as below:

function test(ab: AorB) {
    // can ts auto predict this ?
    if ('a' in ab) {
        console.log(ab.a);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM