Flow: Problem with array type validation?

Created on 6 Mar 2017  路  6Comments  路  Source: facebook/flow

Live Try Flow Example

type TypeThing = {
  id: number
}

type TypePerson = {
  id: number,
  name: string
}

// Case 1
const person: TypePerson = { id: 1, name: 'Ryan' };
const thing: TypeThing = person;

// Case 2
const people: TypePerson[] = [person];
const things: TypeThing[] = people;

// Why does Case 1 pass but Case 2 fail?

Flow has no issues with Case 1, but does complain during Case 2 stating that "property name does not exist in TypeThing".

Why does Flow complain during Case 2, but not Case 1? Does type validation behave differently when Arrays are involved? Is this intended behavior?

Most helpful comment

If you use $ReadOnlyArray instead of Array things will work fine.

type TypeThing = {
  id: number
}

type TypePerson = {
  id: number,
  name: string
}

// Case 1
const person: TypePerson = { id: 1, name: 'Ryan' };
const thing: TypeThing = person;

// Case 2
const people: $ReadOnlyArray<TypePerson> = [person];
const things: $ReadOnlyArray<TypeThing> = people;

All 6 comments

TypePerson is a subclass (or a more specific type) of TypeThing. Case 2 assumes that arrays are covariant.

If you use $ReadOnlyArray instead of Array things will work fine.

type TypeThing = {
  id: number
}

type TypePerson = {
  id: number,
  name: string
}

// Case 1
const person: TypePerson = { id: 1, name: 'Ryan' };
const thing: TypeThing = person;

// Case 2
const people: $ReadOnlyArray<TypePerson> = [person];
const things: $ReadOnlyArray<TypeThing> = people;

Thanks for the great information and a solution. I appreciate it.

@nmn is there a reason why things like $ReadOnlyArray and $Keys are not in the Flow documentation?

@hmillison Yes because the documentation is old. But it is being worked on. Also, the types with $ are generally considered experimental. $ReadOnlyArray is pretty new.

Was this page helpful?
0 / 5 - 0 ratings