无法将TypeScript设置为使用`using`关键字

k10s72fa  于 12个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(123)

我使用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"
    ]
  }
}

和以下文件:

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"

但是我不能使用using关键字,得到错误://无法找到名称'using'. ts(2304)
似乎"esnext.disposable"不被接受。
如何设置TypeScript使用Disposable?谢谢

tag5nh1u

tag5nh1u1#

你的语法是错误的,你还需要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链接
TS博客文章解释新语法

相关问题