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

Can't filter types with Array.filter #1915

Closed
funtaps opened this issue Jun 9, 2016 · 3 comments
Closed

Can't filter types with Array.filter #1915

funtaps opened this issue Jun 9, 2016 · 3 comments

Comments

@funtaps
Copy link

funtaps commented Jun 9, 2016

It's impossible to filter element by type with Array.filter.
Here is example of valid code, that flow don't want to accept.

// @flow
const input: Array<number|string> = [1, 'a', 2, 3, 'b'];
const result: Array<number> = input.filter(el => {
  return typeof el == 'number';
});

It returns

3: const result: Array<number> = input.filter(el => {
                                  ^ call of method `filter`
2: const input: Array<number|string> = [1, 'a', 2, 3, 'b'];
                                  ^^^^^^ string. This type is incompatible with
3: const result: Array<number> = input.filter(el => {
                        ^^^^^^ number

Flow version 0.26.0

@avikchaudhuri
Copy link
Contributor

Duplicate of #1414

@gcanti
Copy link

gcanti commented Jun 26, 2016

@funtaps a possible workaround:

const input: Array<number|string> = [1, 'a', 2, 3, 'b']
const result = ((input.filter(el => {
  return typeof el == 'number'
}): Array<any>): Array<number>)

@bsmith-cycorp
Copy link

bsmith-cycorp commented Jan 17, 2019

Really wish they would solve this. In the meantime, here's a less-gross-but-still-hacky version of the above that we use when we know something is a type but we can't communicate that to Flow:

function cast<T>(val: any): T {
  return val;
}
const input: Array<number|string> = [1, 'a', 2, 3, 'b']
const result = cast<Array<number>>(input.filter(el => typeof el === 'number'))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants