Skip to content

Latest commit

Β 

History

History
74 lines (59 loc) Β· 2.71 KB

File metadata and controls

74 lines (59 loc) Β· 2.71 KB

prefer-dispose

πŸ“ Prefer using using/await using over manual try/finally resource disposal.

🚫 This rule is disabled in the following configs: βœ… recommended, β˜‘οΈ unopinionated.

πŸ’‘ This rule is manually fixable by editor suggestions.

Explicit Resource Management (the using and await using declarations) disposes of a resource automatically when the enclosing block exits, replacing the manual try/finally pattern. It also disposes multiple resources in reverse order and, unlike a hand-written finally, preserves the original error when a disposer throws (via SuppressedError) instead of silently replacing it.

This rule flags a try/finally whose only purpose is disposing of a resource declared just before it, and suggests converting it to a using declaration.

Note

using foo = … requires the value to implement Symbol.dispose (or Symbol.asyncDispose for await using); a value that merely has a .close() method does not qualify and throws a TypeError at runtime. Because this cannot be verified without type information, the rule only offers a suggestion (never an autofix). When type-aware linting is enabled, it additionally confirms the resource is disposable before reporting.

Explicit Resource Management reached Stage 4 and is part of ECMAScript 2026. It ships in recent versions of Node.js and Chromium; for older environments, transpile with TypeScript or Babel.

Examples

// ❌
const file = open();
try {
	read(file);
} finally {
	file.close();
}

// βœ…
{
	using file = open();
	read(file);
}
// ❌
const reader = openReader();
const writer = openWriter();
try {
	pipe(reader, writer);
} finally {
	writer.close();
	reader.close();
}

// βœ…
{
	using reader = openReader();
	using writer = openWriter();
	pipe(reader, writer);
}
// ❌
async function run() {
	const connection = await connect();
	try {
		await query(connection);
	} finally {
		await connection.close();
	}
}

// βœ…
async function run() {
	await using connection = await connect();
	await query(connection);
}