Property “at” does not exist on Array

According to MDN Web Docs Array.prototype#at, is a valid method. But for some reasons, TypeScript refuses to compile, stating that it does not exist.

public at(index: number): V {
  index = Math.floor(index);
  const arr = [...this.values()];
  return arr.at(index);
}

Console output from tsc: Typescript Complains more

I can’t use bracket notation, since the method is meant to be able to handle negative numbers. I’ve tried lots of things, including setting the target in the tsconfig.json file to ESNext, ES2021, and ES6 but to no avail. The lib option doesn’t help either.

json

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2021",
    "outDir": "./dist",
    "declaration": true,
    "declarationDir": "./typings",
    "lib": ["ES2021", "ESNext"]
  }
}

What can I do? Am I doing something wrong?

Answer

According to MDN Web Docs Array.prototype#at, is a valid method.

MDN does not get to decide what is part of TypeScript and what isn’t. The TypeScript developers do that.

Whether or not MDN says something is a “valid method” is relevant to Mozilla, and only Mozilla, but has no bearing on TypeScript.

But for some reasons, TypeScript refuses to compile, stating that it does not exist.

That’s because the method doesn’t exist in any ECMAScript version supported by TypeScript.

I’ve tried lots of things, including setting the target in the tsconfig.json file to ESNext, ES2021, and ES6 but to no avail.

That’s because the method doesn’t exist in either ECMAScript 6 or ECMAScript 2021. It does exist in ES2022 (which is what ESNext is at the moment), but it was only added eight weeks ago, and thus after TypeScript 4.4 was finalized (and possibly also too late for TypeScript 4.5).

The lib option doesn’t help either.

Again, that’s because the method does not exist in any library version supported by TypeScript at the moment.

Even in the current main branch, which is going to become TypeScript 4.6, lib/lib.esnext.d.ts only corresponds to ECMAScript 2021 + the latest Internationalization extensions.

What can I do? Am I doing something wrong?

You can wait until the method actually becomes part of a released version of ECMAScript and/or TypeScript.