Skip to content

add an option to report an error when Symbol.dispose/Symbol.asyncDispose objects are used without the using keywordΒ #63597

Description

@DetachHead

πŸ” Search Terms

dispose using error

βœ… Viability Checklist

⭐ Suggestion

i was surprised to learn that using disposables without the using keyword are not reported as an error:

const foo = {
  [Symbol.dispose]: () => {
    console.log("disposed"); // never called
  },
};

{
  const bar = foo;
  console.log(bar);
}

πŸ“ƒ Motivating Example

the documentation compares it to python with statements. but the whole point of context managers is to enforce that an object is always properly cleaned up. if you forget to use with, then the object's setup is never run so its cleanup doesn't need to run either.

since this is not the case with the using keyword, it should be a type error to use it in an unsafe way

πŸ’» Use Cases

i have an API that i need to log out of when i'm finished using it, otherwise the session remains active

const login = () => {
    // ...
    return {
        [Symbol.asyncDispose]: () => {
            // important cleanup code that MUST be run no matter what
        }
    }
}

in python i would do this with a context manager, and i'd be confident that the cleanup code would always be executed. it's not up to the caller to remember to use the with statement. however in typescript, the caller could easily do this by mistake:

const sesion = await login()
// cleanup code never gets called

this is extremely surprising behavior coming from a language with a similar feature. is this is intentional, the docs should have a clear warning that Symbol.dispose and Symbol.asyncDispose functions have no guarantee to actually be called.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions