[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 @   Zhentiw  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-06-19 [Node] Catch error for async await
2017-06-19 [Jade] Use Mixins in Pug
2017-06-19 [Node] Define MongoDB Model with Mongoose
2016-06-19 [Webpack 2] Intro to the Production Webpack Course
点击右上角即可分享
微信分享提示