patterntypescriptnoneTip
using Keyword for Automatic Resource Disposal
Viewed 0 times
TypeScript 5.2+
usingDisposableSymbol.disposeresource managementcleanup
Error Messages
Problem
Resources like database connections, file handles, and timers require manual cleanup. Try/finally blocks are verbose and easy to forget, leading to resource leaks.
Solution
Implement the Disposable interface and use the 'using' keyword for automatic cleanup at block exit.
// Implement Symbol.dispose
class DatabaseConnection implements Disposable {
constructor(private conn: Connection) {}
query(sql: string) { return this.conn.query(sql); }
[Symbol.dispose]() {
this.conn.close();
console.log('Connection closed');
}
}
// 'using' ensures disposal at end of block (even on throw)
function processData() {
using db = new DatabaseConnection(createConnection());
const rows = db.query('SELECT * FROM users');
return rows; // db[Symbol.dispose]() called here automatically
}
// Async version
class AsyncResource implements AsyncDisposable {
async [Symbol.asyncDispose]() {
await this.cleanup();
}
}
async function run() {
await using res = new AsyncResource();
// res disposed async at end of block
}Why
The 'using' declaration is based on the TC39 Explicit Resource Management proposal. TypeScript 5.2 implements it using Symbol.dispose/Symbol.asyncDispose, modeled after C# 'using' and Python 'with'.
Gotchas
- Requires TypeScript 5.2+ and target ES2022 or later with 'lib: ["ES2022", "ESNext.Disposable"]'.
- Symbol.dispose must be synchronous — for async cleanup use 'await using' with Symbol.asyncDispose.
- The resource is disposed at the end of the block, not when the variable goes out of scope in a wider sense.
Revisions (0)
No revisions yet.