Search code examples
javascriptnode.jstypescriptnodemonts-node

Error cause property not recognized in TypeScript


I stumbled upon the possibility to add a cause to the Error constructor in javascript.

But when I try to use this feature my app does not start as it does not know this "new" constructor arg.

> tsc && node dist/index.js
promo/promo-service/am-promo-request-handler.ts:43:104 - error TS2554: Expected 0-1 arguments, but got 2.        
43         throw new Error(`Can't read Maxmind GeoLite2 City db from mmdb file '${config.pathMmdbCity}'`, { cause: err});
Found 1 error in promo/promo-service/am-promo-request-handler.ts:43 

All of the following commands stop with the above compile error

nodemon
tsc && node dist/index.js
ts-node index.ts

I added the following script to my package.json (to be sure to ask the right instance of node and the other tools for its version)

"check": "nodemon -v && node -v && tsc -v && ts-node -v && npm -v"

It returns

2.0.19
v16.14.2
Version 4.7.4
v10.9.1
8.17.0

The feature should be available since node version 10.9.0

@types/[email protected]

My tsconfig.json

{
  "compilerOptions": {
    "target": "es2017",
    "module": "commonjs",
    "sourceMap": true,
    "outDir": "./dist/",
    "removeComments": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

I'm using VSC on Windows.

Any idea what I need to change/update?


Solution

  • Short answer: cause is only supported in ES2022 and up. You can tell TypeScript to accept it one of two ways via the compilerOptions in tsconfig.json:

    Option 1: Update your target and/or lib to ES2022

    Works if you are able to ignore support for older browsers or polyfill them.

    {
      "compilerOptions": {
        "target": "es2022",
        "lib": ["es2022"],
      },
    }
    
    Option 2: Add just the relevant es2022.error support to lib

    This is a better option if you aren't ready to bump your overall target, and instead just want to include specific well-supported features.

    {
      "compilerOptions": {
        "target": "es2019",
        "lib": ["es2019", "es2022.error"],
      },
    }
    

    Want more nitty gritty detail? Refer to @jsejcksn’s very thorough answer.