如何在数组上使用Flow Intersection Types来扩展自动生成的类型?

时间:2017-06-27 17:07:14

标签: javascript flowtype

Please refer to this example.我需要扩展自动生成的,不可更改的类型。在阵列方面我遇到了麻烦:

// 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

1 个答案:

答案 0 :(得分:2)

似乎流不支持泛型中的那种对象类型的交集。

此示例按预期工作

type beerWithBrand = {
    brand: string
}

type beerWithSize = {
    size: number
}

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

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

编辑:这是预期的行为,因为Array类型的性质(可变)。见https://github.com/facebook/flow/issues/4258