-
Notifications
You must be signed in to change notification settings - Fork 12.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Discriminating between two anonymous types #13459
Comments
In addition to |
One other way of approaching the problem - add an function isFoo(x: any): x is { foo: number } {
return x && typeof x.foo === 'number';
}
function myFunction(x: { foo: number } | { bar: string }) {
if (isFoo(x)) {
x.foo;
} else {
x.bar
}
} |
#10485 tracks treating |
Ah yeah, #10485 is what I want! |
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
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: