Recursion in TypeScript
Our example demonstrates recursive functions in TypeScript. Here’s a classic implementation:
// This `fact` function calls itself until it reaches the
// base case of `fact(0)`.
function fact(n: number): number {
if (n === 0) {
return 1;
}
return n * fact(n - 1);
}
function main() {
console.log(fact(7));
// Closures can also be recursive, but in TypeScript,
// we need to declare the type of the function before
// we define it to allow for recursion.
let fib: (n: number) => number;
fib = (n: number): number => {
if (n < 2) {
return n;
}
// Since `fib` was previously declared, TypeScript
// knows which function to call with `fib` here.
return fib(n - 1) + fib(n - 2);
};
console.log(fib(7));
}
main();
To run this TypeScript code, you would typically compile it to JavaScript and then run it with Node.js:
$ tsc recursion.ts
$ node recursion.js
5040
13
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.