Repository navigation
Open
Labels
accepting prsGo ahead, send a pull request that resolves this issueenhancement: new plugin ruleNew rule request for eslint-pluginpackage: eslint-pluginIssues related to @typescript-eslint/eslint-plugin
Description
Before You File a Proposal Please Confirm You Have Done The Following...
- I have searched for related issues and found none that match my proposal.
- I have searched the current rule list and found no rules that match my proposal.
- I have read the FAQ and my problem is not listed.
My proposal is suitable for this project
- My proposal specifically checks TypeScript syntax, or it proposes a check that requires type information to be accurate.
- My proposal is not a "formatting rule"; meaning it does not just enforce how code is formatted (whitespace, brace placement, etc).
- I believe my proposal would be useful to the broader TypeScript community (meaning it is not a niche proposal).
Description
TypeScript now supports Disposables: objects that have some "dispose" behavior when they go out of scope.
It's important to use using and not const/let when using those objects, otherwise the automatic cleanup does not happen and you would leak resources.
Fail Cases
In this case we are opening a file through an API that expects to be disposed, but we are not using it as such. The readConfig function will thus leak resources associated to the opened file.
declare function openFile(url: string): Disposable & MyFileAPI;
function readConfig() {
const configFile = openFile("./configFile");
return configFile.contentsAsJson();
}Pass Cases
In this case we are properly disposing the file resource.
declare function openFile(url: string): Disposable & MyFileAPI;
function readConfig() {
using configFile = openFile("./configFile");
return configFile.contentsAsJson();
}Additional Info
This is the equivalent to require-await, but for Disposables rather than Thenables.
Reacted by auvred, Yona Appletree, Max Davidson, Kirk Waiblinger, Dawid M., Ryohei Awaka, Autumn Russell, Stefan Schöb, Alec Gibson, Anton Mikhailov and 44 more
Metadata
Metadata
Assignees
Labels
accepting prsGo ahead, send a pull request that resolves this issueenhancement: new plugin ruleNew rule request for eslint-pluginpackage: eslint-pluginIssues related to @typescript-eslint/eslint-plugin
Activity
Josh-Cena commentedon Jan 15, 2024
require-awaitdoesn't require all thenables to be immediately awaited; it requires async functions to contain at least one await. What you want seems slightly related tono-floating-promises. But—isn't one of the design principles of explicit resource management to be opt-in, such that old code can continue to use their own ad-hoc management patterns withoutusing(such astry...catchfor generators)? How do we acknowledge these valid patterns?See also #7160.
nicolo-ribaudo commentedon Jan 15, 2024
Oh yes, I meant
no-floating-promises😅Similarly to disposables, promises also have valid use cases for not being
.then'ed orawaited(one example from code I wrote is to store the promise in a class field). I assume in this case people either do not enable the rule, or disable it for the specific line?Looking more at the code I was writing that prompted be to opening this issue, the mistake I made (and that I wish a linter prevented) is that I forgot
usingbecause I didn't need the value at all. I was migrating from this code:to this:
and the mistake I made was that, since I didn't need the return value of
withVal, I just wrote this:and in this case, there is for sure no alternative cleanup going on because I'm for sure not calling a potential
.cleanup()on the return value ofwithVal.bradzacher commentedon Jan 15, 2024
no-floating-promiseonly tracks expression statements that return a promiserequire-awaitonly ensures async functions either have anawaitor return a promiseSo if you have a non-async function which creates a promise then stores that in a class field - then that promise isn't specifically tracked. It's a blind spot in our lint rules because it is really hard for us to handle based on how TS is designed.
Based on the example in your comment - it does seem like you want a
no-floating-disposablerule - which would be a good thing to build as it very deterministic and bounded - there's not a lot of scope for misinterpretation.OTOH enforcing
usingin your original examples in the OP wouldn't necessarily be correct - because disposing the thing at the end of the function may not be correct. For example one could imagine usecases where a disposable is created in a function, operated on, then a value returned with the intention that this disposable is operated on more and disposed later.Eg imagine a generator style where the disposable reference is captured and privately stored by some wrapper - then eventually disposed when the generator is completed.
From what I've seen so far - there's no good, generic way to enforce disposables themselves are
using'd from what I can tell - not without false-positives on a decent chunk of usecases.Yona-Appletree commentedon Feb 7, 2024
I just ran into this issue, and am now reluctant to use disposables in my code because of the lack of ability to ensure correct usage.
For me, having to bypass the linter warning for the false positives is worth the safety granted by the rule. The vast majority of my potential uses for Disposable would be correctly handled by the proposed rule.
I can imagine that more nuanced and advanced rules might be desired, but I can think of several basic useful ones:
no-floating-disposableDon't allow a Disposable to not be assigned at all (as OP mentioned)no-var-const-let-disposableDon't allow a Disposable to be assigned to alet/const/varvariableThis would cover the most common mistakes. There are certainly some simple cases that wouldn't be covered, like passing the Disposable as a function argument, or accepting one as a parameter. In those cases, it's unclear of the "ownership" of the disposable.
kirkwaiblinger commentedon Mar 5, 2024
bradzacher commentedon Mar 5, 2024
I'm in favour of a rule named
no-misused-disposablethat flags the following:There's an open question as to whether or not we should extend the "does not escape" case above with type-aware assignment checking. EG:
artsiommiksiuk commentedon Apr 16, 2024
JoshuaKGoldberg commentedon Jun 5, 2024
Coming back to this: it looks like we've got a fair bit of community interest, and I'm also in favor. Marking as accepting PRs!
Note that IMO this would likely best be landed in our
strict-type-checkedconfig, notrecommended-type-checked, to start.8 remaining items
bradzacher commentedon Oct 15, 2024
I've been putting a lot of heavy lifting behind the "escapes" keyword.
In your example -- yes it should error because
thingObjectnever "escapes" the closure within which it's defined.We should look at the most common "producers" of disposables: call expressions, new expressions, and variable declarations.
We should analyse these constructs to determine if the value "escapes" the closure.
If the value "escapes" the closure then we do not report on it.
If the value does not "escape" the closure then we do report on it.
By "escapes" I mean that we use scope analysis and similar to determine if the value is either:
So for example:
etc
Yona-Appletree commentedon Jan 3, 2025
This generally seems good, but I am skeptical that passing a
Disposableargument to a function should cause it to "escape" the closure.To be clear, I'm thinking about this example from @bradzacher
Consider:
Am I missing something? What's the rationale behind thinking the disposable "escapes" in a case like this?
kirkwaiblinger commentedon Jan 3, 2025
@Yona-Appletree Why would
interface StreamHandleextendDisposableif it doesn't plan to use it as aDisposable? Why not justbradzacher commentedon Jan 3, 2025
If you pass a disposable to a function and that function is typed to expect that the argument is disposable - then subsequently it is reasonable to assume that the function could dispose of the disposable before it exits.
For example this code could be considered valid
This is the sort of thing in talking about where this rule is really really really really hard to design and reason about.
The goal of my comment is "let us cover all the cases that we can 100% say that a disposable is not disposed because it is created inside a closure and never ever escapes the closure".
The above example creates a disposable inside the closure but then the disposable escapes the closure. Even though it temporarily escapes - it's impossible for us to tell if that temporary escape disposed the disposable or not.
For example a library might be designed such that the user creates a disposable and the library functions consume the disposable and dispose it. We should not error on this case.
van-sprundel commentedon Feb 17, 2025
Just curious, has someone started on a PR for this yet?
JoshuaKGoldberg commentedon Feb 17, 2025
Not visibly, if they did it would show up here. Per https://typescript-eslint.io/contributing/issues/#issue-claiming our policy is that until a PR has been sent, anybody can go ahead and work on it. No "licked cookies" here.
In other words: you're cleared to send a PR 🚀
van-sprundel commentedon Mar 23, 2025
I'll try not to spam this thread too much with my progress, but we ended up making our own "good-enough" rule for this that checks for the keywords.
Here's the rule if anyone want's a temp solution. I only covered very basic test cases here
I'd love to contribute but I don't feel like I have the expertise needed to implement a rule that would cover the given cases
kirkwaiblinger commentedon Apr 17, 2025
I've worked on a rough prototype in #11087 and run into some design questions where the are multiple control flow branches...
For example, given this snippet:
we could either say
If we go with the pessimistic route, it's much trickier to implement (since we don't generally do control flow analysis, though perhaps we can study consistent-return's implementation).
bradzacher commentedon Apr 18, 2025
Pessimism is definitely the way to go because the rule needs to give you confidence that there aren't dangling disposables anywhere.
ESLint has a builtin API for control flow analysis that we can leverage here. But for sure it's a huge chunk of complexity.
Renegade334 commentedon Jun 17, 2025
Just to add weight to this, Node.js has been adding disposability to its existing APIs in earnest, up to and including fundamental features like timers. This proposed rule would error on all existing uses of setTimeout, all existing uses of worker threads, all existing uses of http/net servers... and much more besides.
The proposed rule is predicated on the notion that any Disposable is exclusively intended to be managed through
[await] using. This is fundamentally an incorrect assumption.kirkwaiblinger commentedon Jun 18, 2025
Code using
varwill continue to work too but that's not an argument against ano-varrule... How is this any different?That's... interesting. Certainly that was my intuition, yes, but the
setTimeoutexample in particular is a bit of a head scratcher for me.In any case,
I do think that the default behavior of enforcing all disposables be managed by
usingis the correct approach but agree that flexibility is necessarybradzacher commentedon Jun 18, 2025
NGL part of me hates that design choice - a disposable timer smells bad to me. I saw the old PR adding it but there isn't any justification in the PR... Seems like a bit of an abuse to make something disposable when it's not usually intended to be disposed in most usecases.... Regardless..
This is definitely a valid point though that there is no way for us to differentiate between "a disposable that doesn't need to be disposed" and "a disposable that must be disposed".
I think in general the vast majority of disposables won't be "smelly" like that and turning on the rule will just highlight cases that can be converted to
using.Covering these "not desired to be disposed" cases would be a must to document as part of the first PR...
bradzacher commentedon Jun 18, 2025
We'd also already probably want to add an option to allow you to ignore certain functions / methods?
Otherwise I can see us triggering the same problems and creating the same waves we had with
no-floating-promise...sukima commentedon Aug 9, 2025
Disposable API by design is meant to be opt-in. A disposable resource can and like would be managed by something other than the scope in which it is used. Having the opportunity to pick and choose between
usingorconstmakes perfect sense.Disposable API on a resource can be called multiple times. This could prove useful in some cases.
Disposable API can be opt-out in some cases when you want the things to not be disposed of.
The API design of DisposableStack describes these situations. With this lint even
DisposableStack.move()would be a problem!bradzacher commentedon Aug 9, 2025
The beautiful thing about lint rules @sukima is that they are also opt-in. So if you dislike or disagree with the standards a rule enforces you can opt out.