Kan inte ställa in TypeScript för att använda `using`-nyckelordet
Jag använder TypeScript version 5.2, jag har följande uppställning:
{
"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"
]
}
}
och följande fil:
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"
Men jag kan inte använda using-nyckelordet, får fel:/Kan inte hitta namnet 'using'.ts(2304)
Det verkar som att "esnext.disposable" inte accepteras.
Hur man ställer in TypeScript för att använda disposable? Tack
Svar #1
Din syntax är fel, och du kommer också att behöva polyfilla Symbol.dispose för att få det att fungera i nuvarande JS-miljöer. Följande kommer att fungera:
// <polyfill>
// the interfaces are only necessary if you're not including https://github.com/microsoft/TypeScript/blob/main/src/lib/esnext.disposable.d.ts as a `lib` option
interface SymbolConstructor {
readonly dispose: unique symbol
}
interface Disposable {
[Symbol.dispose](): void
}
// @ts-ignore - if it already exists as a readonly property, this is a no-op anyway
Symbol.dispose ??= Symbol('Symbol.dispose')
// </polyfill>
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-länk
TS-blogginlägg som förklarar den nya syntaxen
