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

Array.find on Array<{...}> raises #3514

Closed
benlangfeld opened this issue Mar 14, 2017 · 2 comments
Closed

Array.find on Array<{...}> raises #3514

benlangfeld opened this issue Mar 14, 2017 · 2 comments

Comments

@benlangfeld
Copy link

Everything below was tested with flow-bin 0.41.0, where the following declaration is in place:

declare class Array<T> extends $ReadOnlyArray<T> {
  ...
  find(callbackfn: (value: T, index: number, array: Array<T>) => any, thisArg?: any): T | void;
  ...
}
/* @flow */

type Foo = {|id: number|}
const foo: Array<Foo> = [{id: 1}, {id: 3}]
const bar: Foo = foo.find((val: Foo) => val.id > 1)
test.js:5
5: const bar: Foo = foo.find((val: Foo) => val.id > 3)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ undefined. Inexact type is incompatible with exact type
5: const bar: Foo = foo.find((val: Foo) => val.id > 3)
              ^^^ exact type: object type

In order to get this past Flow, I have to const bar: any. Curiously, this works:

const bar: Array<Foo> = foo.filter((val: Foo) => val.id > 3)
const baz: Foo = foo.pop()

If I use an inexact type, I get a more generic error:

/* @flow */

type Foo = {id: number}
const foo: Array<Foo> = [{id: 1}, {id: 3}]
const bar: Foo = foo.find((val: Foo) => val.id > 1)
test.js:117
5: const bar: Foo = foo.find((val: Foo) => val.id > 1)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ undefined. This type is incompatible with
5: const bar: Foo = foo.find((val: Foo) => val.id > 1)
              ^^^ object type
@nmn
Copy link
Contributor

nmn commented Mar 14, 2017

The error might be slightly misleading but this is a genuine type-error:
The return type of find is an optional.

Use this in your examples:

const bar: void | Foo = foo.find((val: Foo) => val.id > 1)

@nmn nmn closed this as completed Mar 14, 2017
@benlangfeld
Copy link
Author

@nmn Indeed that does resolve it. Thank you very much for the answer and for being lightning fast.

Now you point it out, it is indeed blindingly obvious. I was expecting to see : ?T and my brain ignored the | void.

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

No branches or pull requests

2 participants