typescript / expert
Snippet
Explicit Async Resource Management using Symbol.asyncDispose
This expert snippet illustrates the Stage 3 Explicit Resource Management feature in TypeScript using `Symbol.asyncDispose` and `await using`. It guarantees reliable asynchronous resource teardown when execution leaves scope, eliminating manual `try...finally` cleanup blocks.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class DatabaseConnection implements AsyncDisposable {private active = true;public async query(sql: string): Promise<unknown[]> {if (!this.active) throw new Error('Connection closed');return [{ id: 1, query: sql }];}async [Symbol.asyncDispose](): Promise<void> {if (this.active) {this.active = false;await new Promise((resolve) => setTimeout(resolve, 10));}}}async function executeTransaction(): Promise<void> {await using conn = new DatabaseConnection();await conn.query('SELECT * FROM users');}
Breakdown
1
class DatabaseConnection implements AsyncDisposable
Implements the global standard AsyncDisposable interface for resource cleanup compliance.
2
async [Symbol.asyncDispose](): Promise<void>
Defines the asynchronous tear-down logic executed automatically upon scope exit.
3
await using conn = new DatabaseConnection();
Uses the resource declaration syntax to bind lifecycle cleanup to the block scope.