Reputation: 951
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
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)
}
}
Upvotes: 2