在流程中如何接受异构数组,并返回该数组

问题描述 投票:0回答:1

当我有一个接受泛型类型的数组并返回转换数组的函数时,我可以写:

function myfun<T>(input: Array<T>): Array<T> {}

但是,如果阵列是异构类型,则会失败,因为T在阵列上是不同的。现在因为我知道T将永远是某个基类的子类型:BaseTy并且在函数期间我只使用来自/对基类型操作的函数,我可以写:

function myfun(input: Array<BaseTy>): Array<BaseTy> {}

然而,这具有实际类型“丢失”的问题,因此该数组不再是派生类型的异构数组。

这可以固定在流量而不诉诸不安全的类型转换或any

javascript generics casting flowtype heterogeneous-array
1个回答
1
投票

您将需要使用bounded generic指定可接受的最小类型,同时还允许函数返回更具体的类型:

function myfun<T: BaseTy>(input: Array<T>): Array<T> {
    // whatever you want to do here
    return input
}

完整代码示例:

type BaseType = {
    base: 'whatever'
}
type TypeA = BaseType & { a: 'Foo' }
type TypeB = BaseType & { b: 'Bar' }
type TypeC = BaseType & { c: 'Baz' }

function myfun<T: BaseType>(input: Array<T>): Array<T> {
    return input
}

const a = {
  base: 'whatever',
  a: 'Foo'
}

const b = {
  base: 'whatever',
  b: 'Bar'
}

const c = {
  base: 'whatever',
  c: 'Baz'
}


const aAndBs: Array<TypeA | TypeB> = [a, b]
const aAndCs: Array<TypeA | TypeC> = [a, c]

// Correct
const xs1: Array<TypeA | TypeB> = myfun(aAndBs)

// Error - It's actually returning Array<TypeA | TypeC>
const xs2: Array<TypeA | TypeB> = myfun(aAndCs)

(Qazxswpoi)

就像Jordan说的那样,如果你遇到Try的麻烦,你可能想把输入数组的类型更改为$ReadOnlyArray

variance
© www.soinside.com 2019 - 2024. All rights reserved.