gpt4 book ai didi

Cannot setup TypeScript to use `using` keyword(无法将TypeScript设置为使用“using”关键字)

转载 作者:bug小助手 更新时间:2023-10-22 16:56:50 33 4
gpt4 key购买 nike



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,我的假设错了吗?

@Radex see stackoverflow.com/questions/52633273/…

@Radex见stackoverflow.com/questions/5263273/…

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com