Javascript 在流程中,如何接受异构数组并返回该数组
当我有一个函数接受泛型类型的数组并返回转换后的数组时,我可以写:Javascript 在流程中,如何接受异构数组并返回该数组,javascript,generics,casting,flowtype,heterogeneous-array,Javascript,Generics,Casting,Flowtype,Heterogeneous Array,当我有一个函数接受泛型类型的数组并返回转换后的数组时,我可以写: function myfun<T>(input: Array<T>): Array<T> {} function myfun(input: Array<BaseTy>): Array<BaseTy> {} 但是,这存在实际类型“丢失”的问题,因此数组不再是派生类型的异构数组 是否可以在不使用不安全类型转换或any的情况下在flow中修复此问题?您需要使用指定可接受的最
function myfun<T>(input: Array<T>): Array<T> {}
function myfun(input: Array<BaseTy>): Array<BaseTy> {}
但是,这存在实际类型“丢失”的问题,因此数组不再是派生类型的异构数组
是否可以在不使用不安全类型转换或any
的情况下在flow中修复此问题?您需要使用指定可接受的最小类型,同时允许函数返回更具体的类型:
function myfun<T: BaseTy>(input: Array<T>): Array<T> {
// whatever you want to do here
return input
}
为什么不像
函数myfun(输入:Array@TheChetan我使用的是flowtype,而不是typescript。但除此之外:它需要我手动向下转换到派生类型:创建我不必制作的副本。(我不希望让flow编写与以前不同的代码)。能否提供有关您试图编写的函数的更多上下文?乍一看,您可能可以使用$ReadOnlyArray
解决此问题,但我需要了解更多详细信息。
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)
function myfun<T: BaseType>(input: $ReadOnlyArray<T>): $ReadOnlyArray<T> {
return input
}