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

Cannot pass Array<T> to a function expecting Array<?T> #4251

Closed
silverlyra opened this issue Jun 26, 2017 · 4 comments
Closed

Cannot pass Array<T> to a function expecting Array<?T> #4251

silverlyra opened this issue Jun 26, 2017 · 4 comments

Comments

@silverlyra
Copy link

silverlyra commented Jun 26, 2017

I just discovered some behavior regarding arrays of maybe types that I found surprising:

const lengths = (strings: Array<?string>): Array<number> =>
    strings.map((s) => s ? s.length : 0)

let strings: Array<string> = ['hello', 'world']
lengths(strings) // Flow error

An Array<T> cannot be passed as an argument for a parameter of type Array<?T>, even though all values in an Array<T> are valid in an Array<?T>. 👉 try flow

Casting via any works, but is nasty. Is this expected behavior? Is there a workaround other than casting to any?

I'm sorry if this is already a reported issue; I couldn't find it.

@omerzach
Copy link
Contributor

I believe the issue is that if the function takes strings: Array<?string> then you're allowed to, e.g., do strings.push(null), which is invalid on an Array<string>.

@popham
Copy link
Contributor

popham commented Jun 27, 2017

If the necessary subtyping were allowed, then lengths could corrupt the type of externalStrings, e.g.

const lengths = (strings: Array<?string>): Array<number> => {
    strings[0] = null; // I've just corrupted `externalStrings`
    strings.map((s) => s ? s.length : 0);
}

let externalStrings: Array<string> = ['hello', 'world']
lengths(externalStrings) // Flow error

@omerzach
Copy link
Contributor

omerzach commented Jun 27, 2017

You can use $ReadOnlyArray now apparently, though not sure if it's documented:
https://github.com/facebook/flow/blob/v0.48.0/lib/core.js#L185
#3425 (comment)

@silverlyra
Copy link
Author

silverlyra commented Jun 27, 2017

I believe the issue is that if the function takes strings: Array<?string> then you're allowed to, e.g., do strings.push(null), which is invalid on an Array<string>.

ahhhhhhhh. right. mutability. never caused anyone any problems. 🙄

thank you – that makes perfect sense. $ReadOnlyArray is perfect for my use case.

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

3 participants