Issue
Is there a way for TypeScript to derive the value of a generic parameter from the type of the parameter that is passed?
Consider the following setup.
type Param<Result> = { bar: Result };
function foo<ResultType, ParamType extends Param<ResultType>>(
value: ParamType
) {
//
}
foo({ bar: "foo" });
I want the ResultType
to be derived from the value passed to foo
, in this case string
. Since I do not explicitly set a value for the ResultType
param, TypeScript defaults to unknown
with
function foo<unknown, {
bar: string;
}>(value: {
bar: string;
}): void
while I want
function foo<string, {
bar: string;
}>(value: {
bar: string;
}): void
The goal is to type the return value of foo
based on Result
. I do not think that the approach works at all, but maybe there is another way to achieve the same result?
I am grateful for every hint!
Solution
If your only goal is to get the return type of foo
based on ParamType
, you could instead say that ParamType
is Param<unknown>
, then using infer
in the return type to get what is "inside":
type Param<Result> = { bar: Result };
function foo<ParamType extends Param<unknown>>(
value: ParamType
): ParamType extends Param<infer U> ? U : never {
// ^^^^^^^ make TypeScript try to infer what's inside
Answered By - caTS
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.