My goal is to restrict the return type of a generic function. Let's simplify with an example.
type MyReturnType<T> = T extends string ? number : Function;
type Input = string | number;
function myFn<T extends string | number>(input: T): MyReturnType<T> {
return typeof input === 'string' ? 100 : (() => {});
}
However, I encountered a TypeScript error due to the return
statement:
Type '100 | (() => void)' is not assignable to type 'MyReturnType<T>'.
Type '100' is not assignable to type 'MyReturnType<T>'.
This confusion arises as I was expecting MyReturnType<T>
to only resolve to a number or a Function. Why is 100 considered unassignable? Is there something I'm missing here? What message is the compiler trying to convey?
I suspect that the explanation lies within the conditional types section of the documentation. However, I may need some clarification since certain aspects are challenging for me to grasp. Can someone decode the logic behind this code snippet for me?
(TS 3.8.3)