2

When transpiling TS to JS compatible with NodeJS v14, using the following config:

{
  "compilerOptions": {
    "lib": ["es2020"],
    "rootDir": "src",
    "outDir": "build",
    "module": "commonjs",
    "moduleResolution": "node",
    "target": "es2020",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipLibCheck": true,
  }
}

It was expected that the usage of at(index) would be converted to a compatible JS code, but in fact, when I ran the built code it generates (...).at is not a function error.

[1,2,3].at(-1)

The transpiled code still makes use of .at(index), but I was expecting it would get transpiled to something compatible with the target set on tsconfig.js

target: "es2020"

What am I not getting correctly here?

felipeclopes
  • 4,010
  • 2
  • 25
  • 35

1 Answers1

3

The TypeScript compiler considers this method as syntactically correct, which is why it does not downlevel it. You can read it better explained in this great answer to a similar question.

However I did not mark your question as duplicate because there is one information that's missing: why don't you have a compiler error?!

If you go to the TS playground, you can see that there is an immediate error if you try to write:

[1, 2, 3].at(0);

Property 'at' does not exist on type 'number[]'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2022' or later.

My guess is that you don't have an error because you are using a wrong version of the package @types/node (most probably the latest one). Indeed, as indicated on node.green, Array.prototype.at() is supported since NodeJS 16.8.0. As such, the latest typings for NodeJS reflect that fact and they provide a signature for that method, which gets automatically included by TSC.

In conclusion, install the same version of NodeJS types as your NodeJS runtime and you should get the TSC error:

npm install @types/node@14
Ben
  • 1,331
  • 2
  • 8
  • 15