TypeScript 5.2's New Keyword: 'using' | Total TypeScript
TypeScript 5.2 will introduce a new keyword - 'using' - that you can use to dispose of anything with a Symbol.dispose function when it leaves scope.
example:
Database connections
Managing database connections is a common use case for using in C#.
Without using:
const connection = await getDb();
try {
// Do stuff with connection
} finally {
await connection.close();
}
With using:
const getConnection = async () => {
const connection = await getDb();
return {
connection,
[Symbol.asyncDispose]: async () => {
await connection.close();
},
};
};
{
await using { connection } = getConnection();
// Do stuff with connection
} // Automatically closed!