-
Notifications
You must be signed in to change notification settings - Fork 13k
Description
Scenario:
Given an indexed object of functions that return different value types, generate a new object with the same indexes and the return value of the functions.
const given = {
foo: () => 1,
bar: () => 'milka',
};
const generatedResult = {
foo: 1,
bar: 'milka',
};
Failing example:
TypeScript is not re-evaluating the Types when calling the function with predictable values:
It can predict the functions and their return types, but it is not evaluating ReturnType<...>
Workaround example:
The proper types are correctly inferred when using an anonymous type directly in the return type of the function:
This workaround is not desired given the need for using the Type definition inside the body of the function.
TypeScript Version: 4.0.3
Search Terms:
- ReturnType
- Generics
Code
function extract<
P extends string,
M extends Record<P, () => any>,
Ret extends {
[K in P]: ReturnType<M[K]>;
}
>(_map: M): Ret {
return <Ret>{};
}
const { foo, bar } = extract({
foo: () => 1,
bar: () => 'bar',
});
Expected behavior:
Variable foo
should be of type number
Variable bar
should be of type string
Actual behavior:
All variables are of type any
Playground Link:
Playground Link or a CodeSandbox Link - Both with the same behavior.