Issue
How can I get return type inference for a generic function whose return type depends on the generic type parameter?
Consider the following:
const foo = <Cond extends boolean>(cond: Cond) => {
return cond ? "a" : "b";
}
type a = ReturnType<typeof foo<true>>; // "a" | "b"
type b = ReturnType<typeof foo<false>>; // "a" | "b"
If I add return type information, the types become correct but TypeScript complains:
const foo = <Cond extends boolean>(
cond: Cond,
): Cond extends true ? "a" : "b" => {
return cond ? "a" : "b"; // Type '"a" | "b"' is not assignable to type 'Cond extends true ? "a" : "b"'.
};
type a = ReturnType<typeof foo<true>>; // "a"
type b = ReturnType<typeof foo<false>>; // "b"
What's the best way to solve this?
Solution
The best solution I could find was to use type assertion on the return value instead of return type information:
const foo = <Cond extends boolean>(
cond: Cond,
) => {
return (cond ? "a" : "b") as Cond extends true ? "a" : "b";
};
type a = ReturnType<typeof foo<true>>; // "a"
type b = ReturnType<typeof foo<false>>; // "b"
Answered By - Magnar Myrtveit
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.