using
Symbol.dispose
https://zenn.dev/ventus/articles/ts5_2-using-preview
https://www.totaltypescript.com/typescript-5-2-new-keyword-using
https://devblogs.microsoft.com/typescript/announcing-typescript-5-2/
https://github.com/microsoft/TypeScript/pull/54505
https://zenn.dev/okunokentaro/articles/01jf78zf9e8y4j7vd351r4w10c
ユースケース
ネットワーク接続を閉じたり、
一時ファイルを削除したり、
メモリを解放したり
usingで宣言された変数は、スコープの終了時にSymbol.disposeメソッドが呼び出される
code:ts
const getResource = () => {
// リソースの初期化処理
...
return {
Symbol.dispose: () => {
// リソースを開放する処理
}
}
}
code:ts
export function doSomeWork() {
using file = getResource();
// ファイルを使用...
if (someCondition()) {
// 追加作業...
return;
}
}// ↑スコープ出る直前にdisposeが呼ばれる
await usingも書ける
AsyncDisposable型
code:ts
function loggy(id: string): AsyncDisposable {
console.log(Constructing ${id});
return {
async Symbol.asyncDispose() {
console.log(Disposing (async) ${id});
await doWork();
},
}
}
await using a = loggy("a");
DisposableStack, AsyncDisposableStack
https://www.totaltypescript.com/typescript-5-2-new-keyword-using
複数のcleanupに便利
usingを使う側が制御できる
code:ts
function doSomeWork() {
const path = ".some_temp_file";
const file = fs.openSync(path, "w+");
using cleanup = new DisposableStack();
cleanup.defer(() => {
fs.closeSync(file);
fs.unlinkSync(path);
});
// ファイルを使用...
if (someCondition()) {
// 追加作業...
return;
}
// ...
}
code:tsconfig.json
{
"compilerOptions": {
"target": "es2022",
"lib": "es2022", "esnext.disposable", "dom"
}
}