[Typescript 5.2] New Keyword: using

TypeScript 5.2 will introduce a new keyword - 'using' - that you can use to dispose of anything with a Symbol.dispose function when it leaves scope.

This can simpfiy the try / finally related code:

function * g() {
  const handle = acquireFileHandle(); // critical resource
  try {
    ...
  }
  finally {
    handle.release(); // cleanup
  }
}

const obj = g();
try {
  const r = obj.next();
  ...
}
finally {
  obj.return(); // calls finally blocks in `g`
}

 

Become:

function * g() {
  using handle = acquireFileHandle(); // block-scoped critical resource
} // cleanup

{
  using obj = g(); // block-scoped declaration
  const r = obj.next();
} // calls finally blocks in `g`

 

File handles

Accessing the file system via file handlers in node could be a lot easier with using.

Without using:

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

let filehandle;
try {
    filehandle = await open("thefile.txt", "r");
} finally {
    await filehandle?.close();
}

With using:

import { open } from "node:fs/promises";
const getFileHandle = async (path: string) => {
  const filehandle = await open(path, "r");
  return {
    filehandle,
    [Symbol.asyncDispose]: async () => {
      await filehandle.close();
    },
  };
};
{
  await using file = getFileHandle("thefile.txt");
  // Do stuff with file.filehandle
} // Automatically disposed!

 

Blog: https://www.totaltypescript.com/typescript-5-2-new-keyword-using

posted @ 2023-06-19 21:38  Zhentiw  阅读(30)  评论(0编辑  收藏  举报