I need to find out the return type based on input values, like in the code below:
type ReturnType<S> = {
array: S extends 'number' ? number[] : S extends 'string' ? string[] : never;
value: S extends 'number' ? number : S extends 'string' ? string : S extends 'object' ? object : never;
}
type FunctionType = {
array: (_: 'number' | 'string') => void,
value: (_: 'number' | 'string' | 'object') => void
};
function determineReturnType<
T extends 'array' | 'value',
S extends FunctionType[T] extends (_: infer Arg) => void ? Arg: never
>(t: T, s: S): ReturnType<S>[T] {}
() => {
const x1 = determineReturnType('array', 'number') // string[] | number[]
const x2 = determineReturnType<'array', 'number'>('array', 'number') // number[]
const y1 = determineReturnType('value', 'number') // string | number | object
const y2 = determineReturnType<'value', 'number'>('value', 'number') // number
}
The above code aims to determine the type of the second argument and the return type from the first argument.
A FunctionType
is provided, which includes mutation functions for the second argument. The second argument's type is extracted from the argument of FunctionType
using the infer
keyword.
However, the compiler struggles to infer the return types of x1
and y1
. Is there a way to improve the inference of generics from the second argument?