在流程中如何接受异构数组,以及return那个数组

In flow how to accept a heterogeneous array, and return that array

当我有一个接受泛型数组和 return 转换数组的函数时,我可以写:

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

然而,如果数组是异构类型,这将失败,因为 T 在数组中是不同的。现在因为我知道 T 将始终是某个基类的子类型:BaseTy 并且在函数期间我只使用函数 from/that 对基类型进行操作,我可以写:

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

然而,这有一个问题,即实际类型是 "lost",因此数组不再是派生类型的异构数组。

是否可以在不诉诸不安全类型转换或 any 的情况下在流程中解决这个问题?

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

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)

(Try)

如 Jordan 所说,如果您 运行 遇到 variance 的麻烦,您可能希望将输入数组的类型更改为 $ReadOnlyArray:

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