Today I Learned using Keyword

TypeScript 5.2 added a new using keyword. This comes from the ECMAScript Explicit Resource Management proposal that allows us to automatically clean up variables when they exit their scope.

This is handy for automatically cleaning up resources when they exit the current scope. Some use cases include:

  • File handles and streams
  • Database connections
  • Locks and synchronization primitives

The using keyword supports both synchronous (Symbol.dispose) and asynchronous (Symbol.asyncDispose) cleanup.

A cool example of this is Node.js's FileHandle class, which configures Symbol.asyncDispose out of the box. This allows you to use the file resource without having to explicitly close it.

import { open, constants } from "node:fs/promises";

async function makeExecutable(path: string): string {
  await using file = await open(path);
  await file.chmod(constants.X_OK);
}

I first learning about this from Total TypeScript.