您需要使用有界泛型来指定可以接受的最小类型,同时还允许函数返回更具体的类型:
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)
(试试)
$ReadOnlyArray
就像乔丹说的那样,如果您遇到方差问题,您可能希望将输入数组的类型更改为:
function myfun<T: BaseType>(input: $ReadOnlyArray<T>): $ReadOnlyArray<T> {
return input
}