Skip to content

Instantly share code, notes, and snippets.

@joewalker
Created May 11, 2017 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joewalker/aee2df2ca3a4381bf1d83a2784a0c0f0 to your computer and use it in GitHub Desktop.
Save joewalker/aee2df2ca3a4381bf1d83a2784a0c0f0 to your computer and use it in GitHub Desktop.
Annoying flow problem
// @flow
type FlatMapMapper<In, Out> = (elem: In, index: number, arr: In[]) => Out | Out[];
function flatMap<In, Out>(arr: In[], mapFunc: FlatMapMapper<In, Out>): Out[] {
const result = [];
for (const [ index, elem ] of arr.entries()) {
const x = mapFunc(elem, index, arr);
// We allow mapFunc() to return non-Arrays
if (Array.isArray(x)) {
result.push(...x);
}
else {
result.push(x);
}
}
return result;
}
function main() {
const input = [ 1, 2, 3 ];
const output: string[] = flatMap(input, i => { return [ 'x' ]; });
output.map(console.log);
}
main();
@joewalker
Copy link
Author

flatmap.js:22
 22:   const output: string[] = flatMap(input, i => { return [ 'x' ]; });
                                                             ^^^^^^^ array literal. This type is incompatible with
 22:   const output: string[] = flatMap(input, i => { return [ 'x' ]; });
                     ^^^^^^ string

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