Search code examples
typescripttypesunion-types

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 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
    }
}


Solution

  • Update your function as below:

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