-
Notifications
You must be signed in to change notification settings - Fork 1.9k
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 a type out of an array of unions #6035
Comments
It's known problem. You can find a lot of issues about this. As a solution you can use reduce or flatMap which can be refined with actual values instead of magical booleans. |
@TrySound - I don't see how either |
Sorry, "or". reduce from array prototype const a = b.reduce((acc, d) => {
if (typeof d === 'number') {
acc.push(d);
}
return acc;
}, []) or flatMap from any library or handwritten or from the future const a = flatMap(b, d => typeof d === 'number' ? [d] : []); they are both easy to type. |
Performance impact with flatMap doesn't matter if you don't work with large arrays. |
Like canvas pixel arrays? :) I think I'll just cast through any for now, as much as I hate doing that |
@markkahn Then reduce as more common version of filter will solve your problem. Just don't use |
What's your reasoning for pushing towards something like reduce vs. casting through any?
|
Dupe of #1414 |
|
of course not, one of its purposes is to bypass the typechecker in exactly situations like this where it fails. Perhaps it's just philosophical, but I'd rather keep the intent of my code correct than jump through weird coding patterns to make flow happy. Though I see your point, and I'd argue for something like this instead: const filteredAry = [];
ary.forEach(v => (typeof v === 'string') && filteredAry.push(v)); |
try flow
bar
is stillArray<string | number>
I also can't annotate
bar
toArray<string>
without casting it throughany
firstThe text was updated successfully, but these errors were encountered: