microsoft / microsoft/TypeScript
add an option to report an error when `Symbol.dispose`/`Symbol.asyncDispose` objects are used without the `using` keyword
还没有人认领这个 Issue。
- 主要语言
- Go
- 星标
- 111k
- 派生
- 14.3k
- 平均合并
- 2 天 4 小时
- 30 天内合并 PR
- 132
描述
### 🔍 Search Terms
dispose using error
### ✅ Viability Checklist
- [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code
- [x] This wouldn't change the runtime behavior of existing JavaScript code
- [x] This could be implemented without emitting different JS based on the types of the expressions
- [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- [x] This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- [x] This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
### ⭐ Suggestion
i was surprised to learn that using disposables without the `using` keyword are not reported as an error:
```ts
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](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#:~:text=that%2E-,You,scope). 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
```ts
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:
```ts
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.
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
未指定实现文件或测试。先从链接的 TypeScript 5.2 发布说明文档以及 issue 中的同步和异步示例开始,然后确定对于未使用 using 而使用的 disposable 对象,预期的诊断和选项行为。完成的标准是报告所要求的误用,同时不改变生成的 JavaScript。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- typescript
- 领域
- compilers
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 冷清
- 描述清晰度
- 基本清楚
- 新手友好度
- 42/100