typescript / expert
Snippet
Explicit Resource Management with 'using'
Introduced in TypeScript 5.2, the 'using' declaration leverages the 'Symbol.dispose' hook to ensure resources like file handles or database connections are cleaned up automatically when the block scope exits, similar to C#'s using or Python's with.
snippet.ts
1
2
3
4
5
6
7
8
9
10
11
class TempFile implements Disposable {constructor(public path: string) {}[Symbol.dispose]() {console.log(`Deleting ${this.path}`);}}function process() {using file = new TempFile("/tmp/log.txt");// File is automatically disposed at end of scope}
Breakdown
1
class TempFile implements Disposable
Defines a class that adheres to the global Disposable interface.
2
[Symbol.dispose]() { ... }
The logic executed immediately when the scope containing the 'using' variable ends.
3
using file = new TempFile(...)
Declares a block-scoped resource that triggers the disposal logic automatically.