← Technical

TIL: TypeScript `using` Keyword

Yesterday I was working with a Sqlite database and I wanted to call db.close() every time a particular class went out of scope. This is a pretty common pattern across programming languages - RAII via destructors in C++, with statements in Python, the Drop trait in Rust – so I was slightly surprised that JavaScript doesn’t have a similar pattern.

Except! Apparently there is an Explicit Resource Management proposal, and TypeScript went ahead and implemented it already!

So we can now add a special [Symbol.dispose] function to a TypeScript class inheriting from Disposable, which will then be run whenever an instance of that class leaves scope, as long as its declared with using. So for example, we can now do this:

export class Cache implements Disposable {
  db: DB;

  constructor(path: string) {
    this.db = new DB(path);
  }
  
  [Symbol.dispose]() {
    this.db.close();
  }
}

// `db.close()` is called when this leaves scope
using cache = Cache("cache.db");

References