Flow: Bug: Aliasing $ReadOnlyArray changes its behavior

Created on 12 Aug 2018  路  2Comments  路  Source: facebook/flow

When using $ReadOnlyArray to avoid having to specify extra data that a function you are calling does not care (to treat data as superTypes) works as expected but if I alias it like this type List<T> = $ReadOnlyArray<T> it stops giving this behavior which unless I'm missing something is a bug :(.

Here is the Try Flow

And here the example code for direct reference:

type List<T> = $ReadOnlyArray<T>

type Films = List<{
  id: number,
  name: string,
  year: string,
  genre: List<string>,
  rating: number,
}>

function parseFilms(films: Films) {
  const bestFilms = getHighestRankedFilms(films) // Error here with List but not with $ReadOnlyArray
  return {
    bestFilms,
    films,
  }
}

type FilmsToRank = List<{
  id: number,
  rating: number,
}>

function getHighestRankedFilms(films: FilmsToRank): Array<number> {
  return films
    .slice()
    .sort((a, b) => (a.rating > b.rating ? -1 : 1))
    .map(film => film.id)
}

I hope it makes sense, if you need me to do something extra let me know :)

Most helpful comment

Make the generic parameter covariant to fix your problem:

type List<+T> = $ReadOnlyArray<T>

All 2 comments

Make the generic parameter covariant to fix your problem:

type List<+T> = $ReadOnlyArray<T>

@jcready awesome, it does the trick

Was this page helpful?
0 / 5 - 0 ratings