TypeScript中的‘using‘关键字的用法

TypeScript5.2引入了using关键字,用于自动管理具有Symbol.dispose或Symbol.asyncDispose函数的资源,如文件句柄和数据库连接。这提高了代码的可维护性和资源释放的自动化程度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

图片

TypeScript 5.2 引入了一个新的关键字 ——  using  —— 你可以用它来处理任何带有  Symbol.dispose  函数的代码,在当它离开作用域时,作一些自动操作。

 
{  const getResource = () => {    return {      [Symbol.dispose]: () => {        console.log('Hooray!')      }    }  }
  using resource = getResource();} // 'Hooray!' logged to console
 

这是基于TC39的提案,最近在JavaScript的进展中达到了阶段3(共4个阶段),这意味着它已经准备好由早期采用者进行测试。

using  对于管理文件句柄、数据库连接等资源非常有用。

Symbol.dispose
 

Symbol.dispose  是 JavaScript 中的一个新的全局符号,任何具有  Symbol.dispose  函数的元素都被认为是一个“资源”——“具有特定生命周期的对象”——并且可以与  using  关键字一起使用。

 
const resource = {  [Symbol.dispose]: () => {    console.log("Hooray!");  },};
 


await using
 

你也可以使用 Symbol.asyncDispose 和 await using 来处理需要异步处理的资源。

const getResource = () => ({  [Symbol.asyncDispose]: async () => {    await someAsyncFunc();  },});
{  await using resource = getResource();}
 

这将在继续之前等待  Symbol.asyncDispose  函数。

这对于数据库连接等资源很有用,在这些资源中,您希望确保在程序继续之前关闭连接。

用例
 

文件句柄
 

使用  using  可以更容易地通过 node 中的文件处理程序访问文件系统。

没有 using :

 
import { open } from "node:fs/promises";
let filehandle;try {  filehandle = await open("thefile.txt", "r");} finally {  await filehandle?.close();}
 


与有 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 = await getFileHandle("thefile.txt");
  // Do stuff with file.filehandle
} // Automatically disposed!
 


数据库连接
 

管理数据库连接是 using 的常见用例。

没有 using :

const connection = await getDb();
try {  // Do stuff with connection} finally {  await connection.close();}
 


与有 using :

const getConnection = async () => {  const connection = await getDb();
  return {    connection,    [Symbol.asyncDispose]: async () => {      await connection.close();    },  };};
{  await using db = await getConnection();
  // Do stuff with db.connection
} // Automatically closed!

  欢迎关注公众号:文本魔术,了解更多

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值