Reputation: 3481
First of all, forgive me if my wording is incorrect, I'm not so familiar with all of the typing jargon.
I have two types: A
and B
, where B
is an extension of A
, like so:
type A = { a: string };
type B = { a: string, b: string };
Asserting that a value of type B
conforms to type A
works fine:
const bar: B = { a: 'hello', b: 'world' };
(bar: A); // No problemo
But when wrapping the value into an array, the assertion goes bad:
const bars: Array<B> = [bar]; // This is fine
(bars: Array<B>); // Also fine
(bars: Array<A>); // Breaks!!
Am I completely misunderstanding something? Is this a Generics problem, an Array problem, or just a bug in Flow?
Flow version: v0.52.0
Check it out yourself on Flow
Upvotes: 0
Views: 263
Reputation: 638
That's because the type parameter T
in Array<T>
is invariant-- meaning it does not accept supertypes or subtypes when considering a subtyping relationship. Check out the docs on variance here for more info on that: https://flow.org/en/docs/lang/variance/#toc-invariance
What you're looking for is a data structure with a covariant type parameter. Specifically, you may want to use $ReadOnlyArray<T>
instead.
Upvotes: 3