closure in typescript

In TypeScript, closures can be implemented using nested functions. A closure is a function that has access to variables in its parent function, even after the parent function has returned.

Here is an example of a closure in TypeScript:

index.ts
function outerFunction() {
  let outerVariable = 'I am outside!';

  function innerFunction() {
    console.log(outerVariable);
  }

  return innerFunction;
}

let closure = outerFunction();
closure(); // logs "I am outside!"
226 chars
13 lines

In this example, outerFunction returns innerFunction. innerFunction has access to the outerVariable in outerFunction, even though outerVariable is not defined in innerFunction. This is because innerFunction is a closure that "closes over" the variables in its parent function.

When outerFunction is called and closure is assigned the result, outerVariable is defined and initialized to 'I am outside!'. When closure is called later with closure(), console.log(outerVariable) logs 'I am outside!'.

As a result, closures are a powerful feature of JavaScript and TypeScript that can be used to create functions with persistent state across multiple invocations.

gistlibby LogSnag