Understanding the "using" Keyword in TypeScript for Resource Management
The new TypeScript `using` keyword lets developers declare disposable resources—objects implementing `Symbol.dispose` or `Symbol.asyncDispose`—so that they are automatically cleaned up (e.g., closing database connections) without manual try/finally code, improving safety and developer experience.
The using keyword can replace const and let to define a disposable object—an object that can clean itself up after use.
Although the keyword originates from C# , TypeScript does not simply copy C#. It selectively adopts the most useful features to improve developer experience.
In this article we explain how the using keyword works in TypeScript and show common scenarios where it is appropriate.
Working Principle
The using keyword can be used like const or let :
using x = getX();This assignment must receive a value or a function that returns a value. Although the assignment is possible, using should only be used for:
Objects that implement the Symbol.dispose method.
Functions that return such objects.
Otherwise, prefer const or let .
Symbol.dispose is a special function in TypeScript that marks an object as a “resource”, i.e., a disposable object.
Example of a disposable resource:
const disposableObject = {
[Symbol.dispose]: () => {
console.log("Dispose of me!");
}
};
using resource = disposableObject;The concept can be extended with await using , which allows asynchronous disposal via Symbol.asyncDispose :
const getResource = () => ({
[Symbol.asyncDispose]: async () => {
await someAsyncFunc();
}
});
{
await using resource = getResource();
}Common Use Case – Database Connection
Database connections are a typical scenario for using . You no longer need to manually close the connection; Symbol.asyncDispose handles it.
Without using (❌):
const connection = await getDb();
try {
// use the connection
} finally {
await connection.close();
}With using (✅):
const getConnection = async () => {
const connection = await getDb();
return {
connection,
[Symbol.asyncDispose]: async () => {
await connection.close();
}
};
};
{
await using db = await getConnection();
// use db.connection
} // automatically closed!This automatic handling gives developers peace of mind and ensures resources are released responsibly.
Conclusion
The using keyword defines “resources”—objects that contain a Symbol.dispose function. Its addition eliminates many accidental bugs and can improve developer experience dramatically.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.