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?
Tried (doesn't work):
return recursion<number, Function>(value+1,lim) Log:
src/main.ts:2:53 - error TS2365: Operator '+' cannot be applied to types 'N' and 'number'. 2 if(value < lim) return recursion<number, Function>(value+1,lim); ~~~~~~~ src/main.ts:2:61 - error TS2345: Argument of type 'N' is not assignable to parameter of type 'number'. 2 if(value < lim) return recursion<number, Function>(value+1,lim); https://stackoverflow.com/questions/65963389/typesafing-recursion-through-generics January 30, 2021 at 08:16AM
没有评论:
发表评论