Original link: https://1link.fun/blog/typescript-using-feature/
TypeScript can be considered as Java in the front-end world. No, TypeScript 5.2 is about to introduce a new keyword: using
. If you are familiar with Java, then the using
keyword is try-with-resource
in the TypeScript world. Its function is that if you use using
to modify any An object containing Symbol.dispose
/ Symbol.asyncDispose
method, when the scope of this object is jumped out, the system will automatically call Symbol.dispose
/ Symbol.asyncDispose
method of this object.
A classic example is the database connection object, before using
, close the database connection object looks like this:
// 获取数据库连接const connection = await getDb (); try { // 使用数据库连接} finally { // 在finally 代码块里关闭连接await connection . close (); }
After using using
, the code looks like this:
// 封装了原始数据库连接的新对象, 并且在Symbol.asyncDispose 异步方法里关闭连接const getConnection = async () => { const connection = await getDb (); return { connection , [ Symbol . asyncDispose ] : async () => { await connection . close (); }, }; }; { // 对于使用者来说, 只需要使用这个新对象即可await using { connection } = getConnection (); // 使用数据库连接} // 出了作用域之后, 会自动调用异步的方法关闭数据库连接
Just thought of the new features of Java 21 before: unnamed class and sample main method , specifically as follows:
void main () { System . out . println ( "Hello, World!" ); }
With this function, the above java code is legal Java entry class code.
This article is transferred from: https://1link.fun/blog/typescript-using-feature/
This site is only for collection, and the copyright belongs to the original author.