Created
May 6, 2018 21:34
-
-
Save emptyother/2c928c661f00ef6d0339bdc52712ec46 to your computer and use it in GitHub Desktop.
Implementing C#'s "IDisposable" pattern in Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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