Skip to content

Instantly share code, notes, and snippets.

@dsherret
Last active October 26, 2023 13:30
Show Gist options
  • Save dsherret/cf5d6bec3d0f791cef00 to your computer and use it in GitHub Desktop.
Save dsherret/cf5d6bec3d0f791cef00 to your computer and use it in GitHub Desktop.
Typescript Disposable (using statement)
// NOTE: This is now rolled up in a package and supports more scenarios: https://github.com/dsherret/using-statement
interface IDisposable {
dispose();
}
function using<T extends IDisposable>(resource: T, func: (resource: T) => void) {
try {
func(resource);
} finally {
resource.dispose();
}
}
// Example use:
class Camera implements IDisposable {
takePicture() { /* omitted */ }
// etc...
dispose() {
navigator.camera.cleanup();
}
}
using(new Camera(), (camera) => {
camera.takePicture();
});
@giano
Copy link

giano commented Sep 2, 2020

Great!

@GokselKUCUKSAHIN
Copy link

Appreciated 👏.

@guftall
Copy link

guftall commented Jan 12, 2022

Nice

@maca134 in case you want to return a value from it

export async function using<T extends IDisposable, U>(resource: T, func: (resource: T) => Promise<U>) {
    try {
        return await func(resource);
    } finally {
        await resource.dispose();
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment