recursive loop in typescript

Here's an example of a recursive loop in TypeScript:

index.ts
function factorial(num: number): number {
  if (num === 0) {
    return 1;
  } else {
    return num * factorial(num - 1);
  }
}

console.log(factorial(5)); // Output: 120
172 chars
10 lines

In this code, the factorial function takes a number as input and returns its factorial by recursively calling itself. The num argument is checked to be 0, in which case the function directly returns 1. Otherwise, it multiplies num with the next number's factorials via a recursive call with num - 1.

Note that recursion can cause stack overflow errors if the recursive function call is not terminated appropriately. So, it must be used carefully and correctly.

gistlibby LogSnag