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
function myFunction(x: { foo: number } | { bar: string }) {
How can I write some code to determine whether x is the first or second type?
Things I've considered:
Writing an x is MyType function to check for a foo property. Yes, I could do this, but it seems overkill for types that are only used as arguments to a single function.
if ((x as { foo: number}).foo) { let y = x as { foo: number }. I could do this, but it defeats the point of a type system. It's also not DRY.
Give them both a common type property. Again, seems like overkill for types that are only used as arguments for one function.
Unify both types into { foo: number, bar?: never } | { bar: string, foo?: never }. This feels like a hack that will confuse other developers when they look at my type signatures.
What I would like would be to do this:
if (x.foo) { /* x has been inferred to be { foo: number } */
Is there a reason that is not possible?
The text was updated successfully, but these errors were encountered:
In addition to if (x.foo) (which would be false if x had a foo with 0 as its value) it would be good if if ('foo' in x) and if (x.hasOwnProperty('foo')) could also do that sort of filtering of the input types.
One other way of approaching the problem - add an isFoo check:
functionisFoo(x: any): x is {foo: number}{returnx&&typeofx.foo==='number';}functionmyFunction(x: {foo: number}|{bar: string}){if(isFoo(x)){x.foo;}else{x.bar}}
Say I have the following code:
function myFunction(x: { foo: number } | { bar: string }) {
How can I write some code to determine whether x is the first or second type?
Things I've considered:
if ((x as { foo: number}).foo) { let y = x as { foo: number }
. I could do this, but it defeats the point of a type system. It's also not DRY.{ foo: number, bar?: never } | { bar: string, foo?: never }
. This feels like a hack that will confuse other developers when they look at my type signatures.What I would like would be to do this:
if (x.foo) { /* x has been inferred to be { foo: number } */
Is there a reason that is not possible?
The text was updated successfully, but these errors were encountered: