eczn
eczn

Reputation: 1801

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

Upvotes: 1

Views: 679

Answers (1)

Krishna Mohan
Krishna Mohan

Reputation: 1722

Update your function as below:

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

Upvotes: 2

Related Questions