Skip to content
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

Interop between discriminated unions and the 'is' operator would be great #19804

Closed
AlexGalays opened this issue Nov 7, 2017 · 3 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@AlexGalays
Copy link

AlexGalays commented Nov 7, 2017

Code

type A = { type: 'a', a: number }
type B = { type: 'b', b: string }
type Union = A | B

const arr: Union[] = [
  { type: 'a', a: 10 },
  { type: 'a', a: 20 },
  { type: 'b', b: '30' }
]

// It should now have been refined as an A[], but is not
const filtered: A[] = arr.filter(x => x.type === 'a')

Expected behavior:

Just like the compiler can infer that the code under a branch following an if (x.type === 'a') can safely use x as an A, it could be able to do it when using an anonymous function in Array.prototype.filter

Actual behavior:

Instead, one must first define a function :

const isA = (u: Union): u is A => u.type === 'a'

and use it to filter the Array. Note that the body of the function is exactly the same as the anonymous function's above, all it does is giving an extra hint to the compiler by way of the return type. Thus, the anonymous function could be automatically picked up to use the proper Array.prototype.filter definition.

Creating lots of isX boilerplate functions is known to be a tedious task for lots of big unions, it would be nice if it wasn't mandatory.

@aluanhaddad
Copy link
Contributor

Seems like a duplicate of #5101

@ghost ghost added the Duplicate An existing issue was already created label Nov 7, 2017
@typescript-bot
Copy link
Collaborator

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@AlexGalays
Copy link
Author

oops, thank you bot.

@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants