Struggling with wrapping a function that can have multiple return types based on input parameters in Typescript.
Imagine wanting a function to return ReturnA
for VariantEnum.a
and ReturnB
for VariantEnum.b
.
Consider this implementation of sampleFunction
:
enum VariantEnum { a, b }
type ReturnA = string
type ReturnB = number
type VariantReturnMap<V> =
V extends VariantEnum.a ? ReturnA :
V extends VariantEnum.b ? ReturnB :
undefined
declare function sampleFunction<V extends VariantEnum>(variant: V): VariantReturnMap<V>
The function works when called directly:
sampleFunction(VariantEnum.a) // returns ReturnA as expected
However, calling it using a wrapper does not work unless re-declaring everything:
function wrapperFunction(variant: VariantEnum) {
// something else
return sampleFunction(variant) // returns (ReturnA | ReturnB) since the variant is unknown
}
wrapperFunction(VariantEnum.a) // still returns (ReturnA | ReturnB)
sampleFunction(VariantEnum.a) // returns ReturnA as expected
Despite TS having enough information to infer the correct return type from the original function, it always defaults to the union type instead.
Is there an alternative solution to get the correct inference without redeclaration?
(The same issue persists when overloading the function with different methods like individual declarations for ReturnA
and ReturnB
)