As of Explicit Resource Management introduced in TypeScript 5.2, with the power of DisposableStack
and AsyncDisposableStack
. You can use defer like this.
function example() {
using cleanup = new DisposableStack();
cleanup.defer(() => console.log('defer'));
console.log('do some work');
}
example();