Let’s set up a (rather contrived) problem to motivate the use of the new using keyword introduced in TypeScript 5.2:
We have a function here that fails sometimes. We want to debug it. We can use console.group to group the logs for this function together. But we need to remember to close the group at the end of the function. If we forget, the groups will continue ad-infinitum, every time the function is called.
Of course, it’s not a big deal to just call console.groupEnd before every return:
But suppose it is a hairy function with many returns. It’s easy to forget to close the group. We can use the using keyword to ensure that the group is closed when the function returns.
To start, we need to polyfill Symbol.dispose, which is still in TC39 stage 3.
Then, we need to define a disposable resource:
When the return value of logGroup leaves scope, it will be disposed. We can use the using keyword for this: