← Back to DAGDA | Support | Source: https://github.com/typescript-eslint/typescript-eslint/issues/8255
Skip to content

Rule proposal: require-using to force using using with disposable #8255

Open

Description

@nicolo-ribaudo

Before You File a Proposal Please Confirm You Have Done The Following...

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.

Activity

  1. added
    enhancement: new plugin rule
    package: eslint-plugin
    triage
    on Jan 15, 2024
  2. Josh-Cena commented on Jan 15, 2024

    @Josh-Cena
    Member

    require-await doesn't require all thenables to be immediately awaited; it requires async functions to contain at least one await. What you want seems slightly related to no-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 without using (such as try...catch for generators)? How do we acknowledge these valid patterns?

    See also #7160.

  3. nicolo-ribaudo commented on Jan 15, 2024

    @nicolo-ribaudo
    Author

    Oh yes, I meant no-floating-promises 😅

    Similarly to disposables, promises also have valid use cases for not being .then'ed or awaited (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 using because I didn't need the value at all. I was migrating from this code:

    let myVal = {};
    
    // somewhere in my code
    {
      const oldMyVal = myVal;
      myVal = { aNewObj: true };
      try {
        // ...
      } finally {
        myVal = oldMyVal;
      }
    }

    to this:

    let myVal = {};
    function withVal(newVal): Disposable {
      const oldVal = myVal;
      myVal = newVal;
      return { oldVal, [Symbol.dispose]: () => myVal = oldVal }
    }
    
    // somewhere in my code
    {
      using _unused = withVal({ aNewObj: true });
      // ...
    }

    and the mistake I made was that, since I didn't need the return value of withVal, I just wrote this:

    // somewhere in my code
    {
      withVal({ aNewObj: true });
      // ...
    }

    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 of withVal.

  4. bradzacher commented on Jan 15, 2024

    @bradzacher
    Member

    Similarly to disposables, promises also have valid use cases for not being .then'ed or awaited (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?

    • no-floating-promise only tracks expression statements that return a promise
    • require-await only ensures async functions either have an await or return a promise

    So 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-disposable rule - 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 using in 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.

  5. Yona-Appletree commented on Feb 7, 2024

    @Yona-Appletree

    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:

    1. no-floating-disposable Don't allow a Disposable to not be assigned at all (as OP mentioned)
    2. no-var-const-let-disposable Don't allow a Disposable to be assigned to a let/const/var variable

    This 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.

  6. added
    evaluating community engagement
    and removed
    triage
    on Feb 7, 2024
  7. kirkwaiblinger commented on Mar 5, 2024

    @kirkwaiblinger
  8. bradzacher commented on Mar 5, 2024

    @bradzacher
    Member

    I'm in favour of a rule named no-misused-disposable that flags the following:

    interface MyDisposable extends Disposable {
        property: string;
    }
    declare function getDisposable(): MyDisposable;
    
    // should report -- easy to implement
    getDisposable();
    if (getDisposable()) {}
    getDisposable().property;
    
    // should report -- harder to implement
    function foo1() {
        const d = getDisposable();
        // variable d does not escape the closure, so should be `using`
    }
    
    // should not report
    function foo2() {
        return getDisposable();
    }
    function foo3() {
        const d = getDisposable();
        return d;
    }
    declare function acceptsAny(v: any): void;
    acceptsAny(getDisposable());

    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:

    declare function acceptsObj(o: { property: string }): void;
    
    function foo4() {
      const d = getDisposable();
      acceptsObj(d);
      // error - disposable does not escape and is passed to a function not expecting a disposable
    }
    
    let thing: { property: string } | null = null;
    function foo5() {
      const d = getDisposable();
      thing = d1;
      // error - disposable does not escape and is assigned to a location not expecting a disposable
    }
  9. artsiommiksiuk commented on Apr 16, 2024

    @artsiommiksiuk
  10. JoshuaKGoldberg commented on Jun 5, 2024

    @JoshuaKGoldberg
    Member

    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-checked config, not recommended-type-checked, to start.

  11. added
    accepting prs
    and removed
    evaluating community engagement
    on Jun 5, 2024
  12. 8 remaining items

  13. bradzacher commented on Oct 15, 2024

    @bradzacher
    Member

    I've been putting a lot of heavy lifting behind the "escapes" keyword.

    In your example -- yes it should error because thingObject never "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:

    • passed to a function
    • returned from a function
    • assigned to a variable declared outside the closure

    So for example:

    {
      // error: disposable does not escape the closure -- needs to be disposed
      declare const disposable: Disposable;
    }
    let x;
    {
      // error: disposable does not escape the closure -- needs to be disposed
      declare const disposable: Disposable;
      x = disposable.foo.bar;
    }
    let x;
    {
      // no error -- disposable escapes the closure
      declare const disposable: Disposable;
      x = disposable;
    }
    declare function someFunction(arg: Disposable) void;
    {
      // no error -- disposable escapes the closure
      declare const disposable: Disposable;
      someFunction(disposable);
    }
    // note: the argument does not have a [Symbol.disposable] key -- so it's not expecting a disposable
    declare function someFunction(arg: {}): void;
    {
      // error: disposable does not escape the closure -- needs to be disposed
      declare const disposable: Disposable;
      someFunction(disposable);
    }
    function foo() {
      // no error -- disposable escapes the closure
      declare const disposable: Disposable;
      return disposable;
    }
    function produceDisposable(): Disposable;
    {
      // error: disposable does not escape the closure -- needs to be disposed
      produceDisposable();
    }
    function produceDisposable(): Disposable;
    {
      // error: disposable does not escape the closure -- needs to be disposed
      produceDisposable().foo.bar;
    }
    function produceDisposable(): Disposable;
    function foo() {
      // no error -- disposable escapes the closure
      return produceDisposable();
    }

    etc

  14. Yona-Appletree commented on Jan 3, 2025

    @Yona-Appletree

    This generally seems good, but I am skeptical that passing a Disposable argument to a function should cause it to "escape" the closure.

    To be clear, I'm thinking about this example from @bradzacher

    declare function someFunction(arg: Disposable) void;
    {
      // no error -- disposable escapes the closure
      declare const disposable: Disposable;
      someFunction(disposable);
    }
    

    Consider:

    interface StreamHandle extends Disposable { /* ... */ }
    
    declare function writeToStream(stream: StreamHandle, value: string) void;
    
    {
      // this seems like it should be an error, writeToStream isn't going to do disposal
      declare const file: FileHandle;
      writeToStream(file);
    }
    
    

    Am I missing something? What's the rationale behind thinking the disposable "escapes" in a case like this?

  15. kirkwaiblinger commented on Jan 3, 2025

    @kirkwaiblinger
    Member

    @Yona-Appletree Why would interface StreamHandle extend Disposable if it doesn't plan to use it as a Disposable? Why not just

    interface StreamHandle { /* ... */ }
    
    declare function writeToStream(stream: StreamHandle, value: string) void;
    
    {
      // this seems like it should be an error, writeToStream isn't going to do disposal (because it doesn't accept a Disposable)
      declare const file: FileHandle;
      writeToStream(file);
    }
  16. bradzacher commented on Jan 3, 2025

    @bradzacher
    Member

    Am I missing something? What's the rationale behind thinking the disposable "escapes" in a case like this

    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

    function someFunction(arg: Disposable & SomeType) void {
      arg.doSomething();
      arg[Symbol.disposable]();
    }
    
    {
      // no error -- disposable escapes the closure
      declare const disposable: Disposable;
      someFunction(disposable);
    }

    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.

  17. van-sprundel commented on Feb 17, 2025

    @van-sprundel

    Just curious, has someone started on a PR for this yet?

  18. JoshuaKGoldberg commented on Feb 17, 2025

    @JoshuaKGoldberg
    Member

    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 🚀

  19. van-sprundel commented on Mar 23, 2025

    @van-sprundel

    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
    /**
     * @fileoverview Enforce proper handling of Disposable objects with using declarations
     */
    
    import { ESLintUtils, TSESTree } from '@typescript-eslint/utils';
    import { createRule } from '../utils.js';
    
    import ts from 'typescript';
    
    export const rule = createRule({
      defaultOptions: [{ ignoreIIFE: false }],
      name: 'no-floating-disposables',
      meta: {
        type: 'problem',
        docs: {
          description: 'enforce proper handling of Disposable objects with using declarations',
          recommended: true,
          requiresTypeChecking: true,
          url: '',
        },
        hasSuggestions: true,
        schema: [],
        messages: {
          floatingDisposable: 'Disposable objects must be declared with using',
          floatingDisposableFixUsing: 'Change declaration to using',
        },
      },
    
      create(context) {
        const services = ESLintUtils.getParserServices(context);
        const checker = services.program.getTypeChecker();
    
        function isDisposable(node: TSESTree.Node): boolean {
          const type = services.getTypeAtLocation(node);
    
          const globalScope = checker.getSymbolsInScope(services.esTreeNodeToTSNodeMap.get(node), ts.SymbolFlags.Interface);
    
          const disposableSymbol = globalScope.find(s => s.name === 'Disposable');
          if (!disposableSymbol) return false;
    
          const disposableType = checker.getDeclaredTypeOfSymbol(disposableSymbol);
          return checker.isTypeAssignableTo(type, disposableType);
        }
    
        return {
          VariableDeclaration(node) {
            if (node.kind === 'using') return;
    
            for (const declaration of node.declarations) {
              if (!declaration.init) continue;
    
              if (isDisposable(declaration.init)) {
                context.report({
                  node,
                  messageId: 'floatingDisposable',
                  suggest: [
                    {
                      messageId: 'floatingDisposableFixUsing',
                      fix: fixer => {
                        const start = node.range[0];
                        const length = node.kind === 'const' || node.kind === 'let' ? node.kind.length : 0;
                        return fixer.replaceTextRange([start, start + length], 'using');
                      },
                    },
                  ],
                });
              }
            }
          },
    
          'ExpressionStatement > CallExpression, IfStatement > CallExpression'(node: TSESTree.CallExpression) {
            if (isDisposable(node)) {
              context.report({
                node,
                messageId: 'floatingDisposable',
                suggest: [
                  {
                    messageId: 'floatingDisposableFixUsing',
                    fix: fixer => {
                      const text = context.sourceCode.getText(node);
                      const parent = node.parent;
    
                      if (parent.type === TSESTree.AST_NODE_TYPES.IfStatement) {
                        return fixer.replaceText(parent, `using disposable = ${text};if (disposable) {}`);
                      }
                      return fixer.replaceText(node, `using disposable = ${text}`);
                    },
                  },
                ],
              });
            }
          },
        };
      },
    });

    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

  20. kirkwaiblinger commented on Apr 17, 2025

    @kirkwaiblinger
    Member

    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:

    declare function makeDisposable(): Disposable;
    
    function maybeReturnsDisposable() {
       const d = makeDisposable();
       if (Math.random() > 0.5) {
          return d;
       } 
       return 42;
    }
    

    we could either say

    • optimistically, the disposable may be handled, so do not flag.
    • pessimistically, the disposable may not be handled, so this should flag.

    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).

  21. bradzacher commented on Apr 18, 2025

    @bradzacher
    Member

    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.

  22. Renegade334 commented on Jun 17, 2025

    @Renegade334
    Contributor

    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 without using (such as try...catch for generators)?

    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.

  23. kirkwaiblinger commented on Jun 18, 2025

    @kirkwaiblinger
    Member

    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 without using (such as try...catch for generators)?

    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.

    Code using var will continue to work too but that's not an argument against a no-var rule... How is this any different?

    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.

    That's... interesting. Certainly that was my intuition, yes, but the setTimeout example in particular is a bit of a head scratcher for me.

    In any case,

    • this is good info to add to the rule docs page, in the "when not to use this rule" section
    • this rule would likely need an allow list, like we have for other rules, so that users can configure types to be ignored.

    I do think that the default behavior of enforcing all disposables be managed by using is the correct approach but agree that flexibility is necessary

  24. bradzacher commented on Jun 18, 2025

    @bradzacher
    Member

    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...

  25. bradzacher commented on Jun 18, 2025

    @bradzacher
    Member

    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...

  26. sukima commented on Aug 9, 2025

    @sukima

    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 using or const makes 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!

  27. bradzacher commented on Aug 9, 2025

    @bradzacher
    Member

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    accepting prsenhancement: new plugin rulepackage: eslint-plugin

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions