disposable-collections
v0.1.0
Published
Objects of disposable things that are disposable themselves
Downloads
1
Readme
disposable-collections
Objects of disposable things that are disposable themselves.
TypeScript 5.2
Using this correctly with NodeJS requires TypeScript 5.2 as well as a polyfill (see example usage below). I wouldn't recommend it for production code yet, since it's still in beta an a lot of important tooling (prettier, eslint, etc) doesn't support it yet.
Installation
- Install TypeScript 5.2 (currently
yarn add -D typescript@beta
ornpm i -D typescript@beta
). - Install this package (
yarn add disposable-collections
ornpm i disposable-collections
).
Usage
import { disposableObject } from "disposable-collections";
// assume we have the following disposable file class
class File {
static open(path): Promise<File>;
read(): Promise<string>;
[Symbol.dispose](): void;
}
// now say we want a function to open a bunch of files
// to use elsewhere
function openFiles() {
return {
foo: await File('foo').open(),
bar: await File('bar').open()
}
}
// this leaks
function doStuff() {
const files = openFiles();
// ...
}
// this is annoying and prone to mistakes
function doStuff() {
const files = openFiles();
using files.foo;
using files.bar;
// ...
}
// this, however, is nice
function doStuff() {
using files = disposableObject(openFiles());
// ...
}
TODO
- ESM support
- Fix prettier (TypeScript 5.2 support in progress: https://github.com/prettier/prettier/issues/15004)
- Fix eslint (TypeScript 5.2 support in progress: https://github.com/typescript-eslint/typescript-eslint/issues/7155)