Recursion in TypeScript
Our example demonstrates recursive functions in TypeScript. Here’s a classic implementation:
To run this TypeScript code, you would typically compile it to JavaScript and then run it with Node.js:
In this TypeScript version:
We’ve defined the
fact
function similarly to the original, using TypeScript’s type annotations to specify that it takes a number and returns a number.The
main
function is not a special function in TypeScript/JavaScript, so we’ve defined it as a regular function and called it at the end of the file.For the recursive closure example, we’ve had to slightly modify the approach. In TypeScript, we declare the type of the
fib
function before defining it, which allows us to use it recursively within its own definition.We’ve used
console.log
instead offmt.Println
for output.The execution demonstrates the same results as the original example, showing the factorial of 7 (5040) and the 7th Fibonacci number (13).
This example showcases how TypeScript supports recursive functions, both as standalone functions and as closures, while providing type safety.