2

I've realized that any recursive function will hit no-unused-vars error which I don't understand why

Simple recursion as below

const factorial = (x: number) => {
  if (x === 0) return 1;

  return x * factorial(x - 1);
};

enter image description here

2
  • If you change const to var does it still occur? Sep 20, 2021 at 6:51
  • @TusharShahi: yes still getting it
    – Isaac
    Sep 20, 2021 at 6:52

1 Answer 1

3

Here is the thing: if you declare a variable that is not exported (that means it cannot be used outside the file), you will have to use it in the file or export the function. So, you could do either this:

export const factorial = (x: number): number => {
  if (x === 0) return 1;

  return x * factorial(x - 1);
};

or call the function in the file:

const factorial = (x: number): number => {
  if (x === 0) return 1;

  return x * factorial(x - 1);
};

factorial(42);

See here: https://tsplay.dev/w11ekw

1
  • interesting, i was expecting the error to be thrown at the factorial beside const instead of the inner factorial. Personally will feel that the location of the error is a mistake but oh well...
    – Isaac
    Sep 20, 2021 at 7:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.