Austaras
Austaras

Reputation: 951

Tell varible is which one of the union type

interface X {
    x: number
    z: string
}
interface Y {
    x: number
    y: number
}

type XY = X | Y
function foo(arg: XY) {
    if (arg.y) {
        console.log(arg.x + arg.y)
    }
}

I want to check if arg is X or Y, the most intuitive way seems like to check if there is y in arg, however TSC doesn't allow this.

What's the right way?

Upvotes: 0

Views: 29

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250056

An in type guard will work best in this case:


interface X {
    x: number
    z: string
}
interface Y {
    x: number
    y: number
}

type XY = X | Y
function foo(arg: XY) {
    if ('y' in arg) {
        console.log(arg.x + arg.y)
    }
}

Play

Upvotes: 2

Related Questions