繁体   English   中英

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

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

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

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

但是,如果数组为异构类型,则此操作将失败,因为T随数组而不同。 现在,由于我知道T将始终是某个基数的子类型: BaseTy并且在该函数期间,我仅使用来自/在该基类型上进行操作的函数,因此我可以这样写:

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

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

可以在不依靠不安全的类型转换或any情况下固定流中的内容吗?

您将要使用有界的泛型来指定可以接受的最小类型,同时还允许该函数返回更特定的类型:

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)

尝试

就像Jordan所说的那样,如果遇到方差问题,您可能需要将输入数组的类型更改为$ReadOnlyArray

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM