Typesafing Recursion Through Generics?
I'm trying to find a way to typesafe a recursion (which returns a number by the end) using generics.
What I tried:
function recursion<N,T>(value:N, lim:N):T|N {
if(value < lim) return recursion<N, T>(value+1,lim);
return value;
}
recursion<number, Function>(0,10);
Despite passing type number
, Typescript decided to give me an error:
TSError: ⨯ Unable to compile TypeScript:
src/main.ts:2:41 - error TS2365: Operator '+' cannot be applied to types 'N' and 'number'.
2 if(value < lim) return recursion<N, T>(value+1,lim);
I assumed that operations were possible as long as I passed number
type on the generic, but it doesn't seem to be the case. Why is that and is there any possible workaround?
from Recent Questions - Stack Overflow https://ift.tt/3amAEXw
https://ift.tt/eA8V8J
Comments
Post a Comment