Kiechlus
Kiechlus

Reputation: 1237

How to use Flow Intersection Types on Arrays to extend an auto-generated type?

Please refer to this example. I need to extend an autogenerated, unchangable type. I run into troubles when it comes to arrays:

// Auto created and imported object.
// Cannot be changed.
// Should be extended
type Drinks = {
  // many other stuff
  beers: Array<{
    brand: string
  }>
}

type ExtendedBeer = {
  size: number
}

type DrinksExtended = Drinks & {beers: Array<ExtendedBeer>} // Throws

const myDrink: DrinksExtended = {
  beers: [{brand: 'Rothaus', size: 0.5}]                            
}

myDrink.beers.map(beer => beer.size) // Throws: `size`. Property not found

Upvotes: 0

Views: 190

Answers (1)

cnexans
cnexans

Reputation: 994

Seems flow does not support that kind of intersection of object types within generics.

This example works as expected

type beerWithBrand = {
    brand: string
}

type beerWithSize = {
    size: number
}

type beerStock = {
    beers: Array<beerWithBrand & beerWithSize> 
}

var stock : beerStock = {beers : [{brand: 'Rothhaus', size: 0.5}]} 

Edit: this is the expected behavior because of the nature of the Array type (mutable). See https://github.com/facebook/flow/issues/4258


Upvotes: 2

Related Questions