I am using TypeScript 5.2 version, I have following setup:
我使用的是TypeScript 5.2版本,我有以下设置:
{
"compilerOptions": {
"target": "esnext",
"module": "commonjs",
"noImplicitAny": true,
"esModuleInterop": true,
"noEmitOnError": true,
"moduleDetection": "force",
"noUnusedLocals": false,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"lib": [
"esnext",
"esnext.disposable", // Value is not accepted.
"dom"
]
}
}
and the following file:
以及以下文件:
const getFile = () => {
return {
[Symbol.dispose]: () => {
console.log('x!')
}
}
}
console.clear()
using(const file = getFile()) { // ERROR: Cannot find name 'using'.ts(2304)
// do something with file
}
"ts-node": "^10.9.1",
"typescript": "^5.2.2"
But I cannot use the using
keyword, get error: // Cannot find name 'using'.ts(2304)
但是我不能使用using关键字,得到错误://找不到名称'using'.ts(2304)
It seems that "esnext.disposable"
is not accepted.
看来“esnext.一次性”是不被接受的。
How to setup TypeScript to use disposable? Thanks
如何设置TypeScript使用一次性?谢谢
更多回答
优秀答案推荐
Your syntax is wrong, and you'll also need to polyfill Symbol.dispose
to get it to work in current JS environments. The following will work:
您的语法是错误的,您还需要polyfill Symbol.dispose才能使其在当前的JS环境中工作。以下内容将起作用:
// polyfill
const dispose = Symbol('Symbol.dispose')
interface SymbolConstructor {
dispose: typeof dispose
}
Symbol.dispose ??= dispose
// code
const getFile = () => {
return {
[Symbol.dispose]: () => {
console.log('x!')
}
}
}
console.log(1)
// note the enclosing block, which acts as the scope for the resource
{
using file = getFile()
console.log(2)
}
console.log(3)
// console output: 1, 2, "x!", 3
TS Playground link
TS游乐场链接
TS blog post explaining the new syntax
TS博客文章解释新语法
更多回答
I thought TypeScript will generate the polyfill by using "esnext", is my assumption wrong?
我以为TypeScript会使用“esnext”生成polyfill,我的假设错了吗?
我是一名优秀的程序员,十分优秀!