Skip to content

Instantly share code, notes, and snippets.

@emptyother
Created May 6, 2018 21:34
Show Gist options
  • Save emptyother/2c928c661f00ef6d0339bdc52712ec46 to your computer and use it in GitHub Desktop.
Save emptyother/2c928c661f00ef6d0339bdc52712ec46 to your computer and use it in GitHub Desktop.
Implementing C#'s "IDisposable" pattern in Typescript
interface Disposable {
dispose(): void;
}
function using<T extends Disposable>(instance: T, fn: (instance: T) => any) {
try {
fn(instance);
} finally {
instance.dispose();
}
}
class MyDisposableClass {
constructor(public text: string) {
}
public dispose() {
delete this.text;
}
}
// Testing:
let outsideRef: MyDisposableClass;
using(new MyDisposableClass('Test'), instance => {
outsideRef = instance;
console.log(instance.text); // 'Inside using: Test'
});
console.log(outsideRef.text); // undefined
let outsideRef2: MyDisposableClass;
try {
using(new MyDisposableClass('Test2'), instance => {
outsideRef2 = instance;
console.log(instance.text); // 'Test2'
throw new Error(); // What if an error happened here?
});
} catch (ex) {
// Ignore error
}
console.log(outsideRef2.text); // Still undefined despite the exception
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment