I have a Backend that provides me with data, that could be of different types in the same Array. This data should be seperated and handled differently for each type.
This is a simplified Version of the used Code:
type ReturnTypeInferer<T> = T extends (a: object) => infer U ? U : never;
interface TypeMap {
'a': (val: object) => number | null,
'b': (val: object) => string | null,
}
const typeFunctions: TypeMap = {
'a': () => null,
'b': () => null
};
function isNotNull<T>(v: T | undefined | null): v is T {
return v != null;
}
function f<U extends keyof TypeMap>(type: U): ReturnTypeInferer<TypeMap[U]>[] {
const applications: object[] = [];
// Response definition
const result = applications
.map<ReturnTypeInferer<TypeMap[U]>>(typeFunctions[type])
.filter(isNotNull);
return result;
}
The return type of f() is actually ok but Typescript does not like the function call in .map: typeFunctions[type] =>
Argument of type '((val: object) => number) | ((val: object) => string)' is not assignable to parameter of type '(value: object, index: number, array: object[]) => ReturnTypeInferer<TypeMap[U]>'.
Type '(val: object) => number' is not assignable to type '(value: object, index: number, array: object[]) => ReturnTypeInferer<TypeMap[U]>'.
Type 'number' is not assignable to type 'ReturnTypeInferer<TypeMap[U]>'.ts(2345)
If I omit the .map's type argument, result evaluates to the first returntype within TypeMap. So now its number[], but if you switch the lines ist string[].
Is this a Bug?