如何在 TypeScript 中使用可选链?

mpe*_*pen 15 typescript optional-chaining

看起来可选链接已经登陆这是一个例子

我想不通的是如何让 TS 正确编译它。我的项目中没有出现任何语法错误,但是:

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

正在输出为:

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

在我们获得 Node.js 的原生支持之前,它不会运行。

这是我的 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"
    ]
}
Run Code Online (Sandbox Code Playgroud)

我需要启用其他选项来编译?.运算符吗?

请注意,我没有使用 Babel,也不想将其带入图片中。

Tit*_*mir 21

问题是您的目标是esnext这将告诉编译器按原样输出所有语言功能,而无需任何转换。将语言设置为 es2020(或更低)?.??并将被转换为兼容代码:

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

游乐场链接

没有细粒度控制哪些语言特性被转译,哪些不需要你不幸地选择一个整体,

  • 问题是我也在使用 BigInts,它已经被节点支持了一段时间了:-(“TS2737:当目标低于 ESNext 时,BigInt 文字不可用” (6认同)
  • 升级到 **TypeScript 3.8** 后,我再次遇到同样的问题。我认为你实际上应该以“es2019”为目标,以便“填充”可选链。 (6认同)
  • @icl7126 是对的。对于 **TS 3.8.3**,您必须将 `ES2019` 设置为目标 (3认同)
  • 设置 `target: ES2019` 对于 **TS 3.9.5** 仍然有效 (2认同)

mpe*_*pen 5

好吧,我不想使用 Babel,因为那样我就必须弄清楚如何替换ts-node. 有一堆过时的文档引用了旧的 Babel 软件包,但这些说明应该在 2019 年 11 月起有效:

添加.babelrc文件:

{
    "presets": [
        ["@babel/preset-env",{"targets": {"node": "current"}}],
        "@babel/preset-typescript"
    ],
    "plugins": [
        "@babel/plugin-syntax-bigint"
    ]
}
Run Code Online (Sandbox Code Playgroud)

添加这些部门:

  "devDependencies": {
    "@babel/cli": "^7.7.0",
    "@babel/core": "^7.7.0",
    "@babel/node": "^7.7.0",
    "@babel/plugin-syntax-bigint": "^7.4.4",
    "@babel/preset-env": "^7.7.1",
    "@babel/preset-typescript": "^7.7.0",
    "@types/node": "^12.7.5",
    "typescript": "^3.7.2"
  }
Run Code Online (Sandbox Code Playgroud)

使用以下命令执行您的代码:

node_modules/.bin/babel-node --extensions ".ts" src/index.ts
Run Code Online (Sandbox Code Playgroud)

--extensions ".ts"非常重要,即使您明确尝试执行 .ts 文件,它也不会转译它。

我喜欢使用 GNU Make 而不是 package.json 脚本:

MAKEFLAGS += --no-builtin-rules
.SUFFIXES:
NM := node_modules/.bin
.PHONY: build start dev clean test publish

## commands
########################################

__default:
    $(error Please specify a target)

build: build-types build-js dist/package.json

build-types: node_modules/.yarn-integrity
    $(NM)/tsc --emitDeclarationOnly

build-js: node_modules/.yarn-integrity
    $(NM)/babel src --out-dir dist --extensions ".ts" --source-maps inline

run: node_modules/.yarn-integrity
    $(NM)/babel-node --extensions ".ts" src/index.ts

check: node_modules/.yarn-integrity
    $(NM)/tsc --noEmit

dist:
    mkdir -p $@

clean:
    rm -rf node_modules dist yarn-error.log

dist/package.json: package.json | dist
    jq 'del(.private, .devDependencies, .scripts, .eslintConfig, .babel)' $< > $@

## files
########################################

node_modules/.yarn-integrity: yarn.lock
    @yarn install --frozen-lockfile --production=false --check-files
    @touch -mr $@ $<

yarn.lock: package.json
    @yarn check --integrity
    @touch -mr $@ $<
Run Code Online (Sandbox Code Playgroud)

或者直接从Microsoft 的 TypeScript Babel Starter复制。