TypeScript'i `using` anahtar kelimesini kullanacak şekilde ayarlayamıyor


TypeScript 5.2 sürümünü kullanıyorum, elimde aşağıdaki kurulum var:

{
  "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"
    ]
  }
}

ve aşağıdaki dosya:

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"

Ama using anahtar kelimesini kullanamıyorum, hata alıyorum:/'using' adı bulunamıyor.ts(2304)

Görünüşe göre "esnext.disposable" kabul edilmiyor.

TypeScript'i disposable kullanacak şekilde nasıl ayarlayabilirim? Teşekkürler

Cevap #1

Söz diziminiz yanlış ve mevcut JS ortamlarında çalışması için Symbol.dispose için polyfill de eklemeniz gerekecek. Aşağıdaki işe yarayacaktır:

// <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 bağlantısı

Yeni sözdizimini açıklayan TS blog yazısı