How to get optional chaining working in TypeScript?

mpen picture mpen · Nov 6, 2019 · Viewed 20.1k times · Source

Looks like optional chaining has landed. Here's an example

What I can't figure out is how to get TS to compile it properly. I'm not getting any syntax errors in my project, but this:

let imageFileId = (await db.query(sql`select id from image_files where sha256=${sha256}`))[0]?.id;

Is being output as:

let imageFileId = (await db.query(mysql3_1.sql `select id from image_files where sha256=${sha256}`))[0]?.id;

Which won't run until we get native support in Node.

Here's my tsconfig:

{
    "compilerOptions": {
        "strict": true,
        "importHelpers": false,
        "inlineSources": true,
        "noEmitOnError": true,
        "pretty": true,
        "module": "commonjs",
        "noImplicitAny": true,
        "suppressImplicitAnyIndexErrors": false,
        "removeComments": false,
        "preserveConstEnums": false,
        "sourceMap": true,
        "lib": ["es2018"],
        "skipLibCheck": false,
        "outDir": "dist",
        "target": "esnext",
        "declaration": false,
        "resolveJsonModule": true,
        "esModuleInterop": false,
        "moduleResolution": "node",
        "allowSyntheticDefaultImports": true,
        "baseUrl": ".",
        "paths": {
            "*": ["src/*"]
        },
        "noEmit": false
    },
    "files": [
        "src/index"
    ],
    "include": [
        "src/**/*.d.ts"
    ]
}

Is there some other option I need to enable to compile the ?. operator?

Please note I'm not using Babel and I don't want to bring it into the picture.

Answer

Titian Cernicova-Dragomir picture Titian Cernicova-Dragomir · Nov 6, 2019

The problem is you are targeting esnext this will tell the compiler to output all language features as is without any transpilation. Set the language to es2020 (or below) and ?. and ?? will get transpiled to compatible code:

(async function () {
    let imageFileId = (await db.query(sql`select id from image_files where sha256=${sha256}`))[0]?.id;
})()

Playground Link

There is no fine-grained control over which language features get transpiled and which don't do you have to pick a version as a whole unfortunately,