12
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ts-node で Optional Chaining コンパイルエラー解決法

Last updated at Posted at 2020-03-11

Optional Chaining とは

TypeScript 3.7 から導入される新機能で、?.という新しい構文です。より簡潔なコードが書けます。

従来の方法
// データ取得
if (adventurer.dog) {
  console.log(adventurer.dog.name);
}

// 関数実行
adventurer.someNonExistentMethod & adventurer.someNonExistentMethod();
Optional-Chaining
// データ取得
console.log(adventurer.dog?.name);
// expected output: undefined

// 関数実行
console.log(adventurer.someNonExistentMethod?.())
// expected output: undefined

ts-nodeで実行すると...

return this.agent.context?.contexts[name]?.parameters[key];
                         ^
SyntaxError: Unexpected token '.'
    at Module._compile (internal/modules/cjs/loader.js:892:18)
    at Module.m._compile (C:\Project\VirtualAssitant\dxc\backend\node_modules\ts-node\src\index.ts:814:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Object.require.extensions.<computed> [as .ts] (C:\Project\VirtualAssitant\dxc\backend\node_modules\ts-node\src\index.ts:817:12)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Module.require (internal/modules/cjs/loader.js:849:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (C:\Project\VirtualAssitant\dxc\backend\src\fulfillment\index.ts:4:1)
    at Module._compile (internal/modules/cjs/loader.js:956:30)

解決方法

Webpack使う場合

@babel/plugin-proposal-optional-chaining プラグインをインスタンスする

webpack.config

const configs: Configuration = {
  ...
  module: {
    rules: [
      {
        test: /\.(tsx|ts)$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              plugins: ['@babel/plugin-proposal-optional-chaining']
            }
          },
          {
            loader: 'ts-loader',
            options: {
              transpileOnly: true,
              happyPackMode: true
            }
          }
        ]
      },
  },
  ...
};

Webpack以外の場合

tsconfig.jsontargetES2018に修正する

tsconfig.json
{
  "compilerOptions": {
    "target": "ES2018" 
    ...
  },
  ...
}

それでも解決できない場合

typescriptts-nodeなどのライブラリバージョンアップをおすすめです。

12
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?