TypeScript · Senior · Question 28 of 75
What are using declarations (TS 5.2) for?
{
using file = openFile('log.txt');
// ...
} // file[Symbol.dispose]() is called automatically- ✓Correct answer: Automatically calling
Symbol.disposewhen leaving the block - 2Importing modules inside a block of code, like
importin Python - 3A replacement for
constfor deeply immutable objects
Explanation
It implements the ECMAScript Explicit Resource Management proposal: the resource is released even if an exception is thrown - like try/finally, but shorter. For async resources there's await using and Symbol.asyncDispose. Handy for connections, files, locks and subscriptions in tests.