Open In App

What is the using Keyword in Typescript ?

The new version of TypeScript introduces support for the “using” keyword used for the Explicit Resource Management feature in the ECMAScript, the using keyword is a keyword that aims to sort the facility for “cleanup” after creating any object.

The need for “using” keywords in both TypeScript and JavaScript is because it allows the developers to perform necessary actions like closing the connections for the network, release of memory, deletion of temporary files, etc.



Keywords in TypeScript

Keywords in programming languages such as TypeScript or JavaScript are reserved words that have some specific meaning, any keyword can not be used as an identifier because an identifier must follow rules in the naming of functions, variables, etc.

There are many keywords in the TypeScript such as let, const, var, and loop keywords such as for, while, do, etc. Another keyword that is recently being discussed in TypeScript is the “using” keyword which is gaining popularity, so it becomes important to understand how the using keyword can be used if it is implemented by the TypeScript organization successfully.



Using Keywords in TypeScript

Using keyword will become a useful keyword for the management of the resources specifically when the resources are bounded by a specific amount of time or when the resource needs to be closed after using it, for example, one resource like this might be the database connections that needs to be closed or released after it is used.

Example:

{
  const getResource = () => {
    return {
      [Symbol.dispose]: () => {
        console.log(Welcome from GeeksforGeeks!')
      }
    }
  }

  using resource = getResource();
} // Welcome from GeeksforGeeks! Will be logged to the console.

Code Explanation:

The above code has a const keyword which is being used for constructing the getResource function that returns the value to the console.log. Here symbol. dispose is being used which is not available in the new releases of typescript because as we have discussed the keyword itself is in the discussion phase and isnt available for the public. In the next line of the code, a keyword is used to define a resource from the getResource() function to return the console.log message.

Article Tags :