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

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


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

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


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

可以在不依靠不安全的类型转换或any的情况下解决此问题吗?

最佳答案

您将要使用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)



Try

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

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

关于javascript - 在流中,如何接受异构数组并返回该数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54823338/

10-12 00:35
查看更多