You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Suppose I have a union of two types which are completely distinguishable based on their keys:
typeFoo={x: number}|{y: string}
I'd like to do case analysis on this union in a typesafe way. I would think using in would work, but it doesn't:
functionf(foo: Foo){if('x'infoo){// Type error: Property 'x' does not exist on type '{ y: string; }'console.log(foo.x+5)}else{// Type error: Property 'y' does not exist on type '{ x: number; }'console.log(foo.y.length)}}
However I'm able to define a type guard which does the trick:
exportfunctionhasKey<Kextendsstring>(k: K,o: {}): o is {[_inK]: {}}{returntypeofo==='object'&&kino}// Now this works:functionf(foo: Foo){if(hasKey('x',foo)){console.log(foo.x+5)}else{console.log(foo.y.length)}}
Is there a more correct built-in way to do this that I'm missing? It seems like this is something in should provide out of the bag.
The text was updated successfully, but these errors were encountered:
Suppose I have a union of two types which are completely distinguishable based on their keys:
I'd like to do case analysis on this union in a typesafe way. I would think using
in
would work, but it doesn't:However I'm able to define a type guard which does the trick:
Is there a more correct built-in way to do this that I'm missing? It seems like this is something
in
should provide out of the bag.The text was updated successfully, but these errors were encountered: