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<A|B> should be compatible with Array<A> #3425

Closed
aldendaniels opened this issue Feb 23, 2017 · 8 comments
Closed

Array<A|B> should be compatible with Array<A> #3425

aldendaniels opened this issue Feb 23, 2017 · 8 comments

Comments

@aldendaniels
Copy link

This:

declare function func(things: Array<string | number>): void;
declare var value: string[];
func(value);

Gives:

1: declare function func(things: Array<string | number>): void;
                                                ^ number. This type is incompatible with
2: declare var value: string[];
                      ^ string
@aldendaniels
Copy link
Author

Perhaps related: #2507

@omerzach
Copy link
Contributor

omerzach commented Feb 23, 2017

Arrays are invariant: T being a subtype of U does not mean Array<T> is a subtype of Array<U>. Otherwise you could push a number onto things inside of func and there would be a number in value, which has type Array<string>.

@jesseschalken
Copy link
Contributor

Can't because func(value) could add a number to value.

function func(things: Array<string | number>): void {
  things.push(1);
}
var value: string[] = ['f'];
func(value);
console.log(typeof value[1]); // a number!

@aldendaniels
Copy link
Author

@jesseschalken @omerzach Wow, thanks for the quick follow up! Is there a way to make flow allow this if the function doesn't mutate the array - e.g. using a readonly array?

@jesseschalken
Copy link
Contributor

You can use func<T:string|number>(things: Array<T>): void or, of any Iterable will do, func(things: Iterable<string|number>): void (Iterable<T> is covariant in T).

@jesseschalken
Copy link
Contributor

See also #2333

@aldendaniels
Copy link
Author

@jesseschalken Sure enough! func(things: $ReadOnlyArray<T>) also appears to work

@aldendaniels
Copy link
Author

Closing in favor of #2333

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