[Typescript 5.2] New Keyword: using

发布时间 2023-06-19 21:44:20作者: Zhentiw

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: