Closures in TypeScript
TypeScript supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.
To run this TypeScript code, you would typically use the TypeScript compiler (tsc
) to compile it to JavaScript, and then run the resulting JavaScript with Node.js. Here’s how you might do that:
In TypeScript, closures work in a very similar way to many other languages. The intSeq
function returns an anonymous function that has access to the i
variable in its outer scope. Each time this returned function is called, it increments and returns the value of i
.
The main
function demonstrates how this closure works. It creates two separate instances of the counter (nextInt
and newInts
), showing that each maintains its own independent state.
The last feature of functions we’ll look at for now is recursion.