Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.at() method missing from typescript array type

With:

const myArray = [0,4,2];
myArray.at(-1);

I get the following error under .at

Property 'at' does not exist on type 'number[]'.ts (2339)

What's going on here why doesn't Array.at() work? Do I have to set some sort of browserlist value to let TS know that I want to be able to use this (recently spec'd) feature?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at

Here's my tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "useDefineForClassFields": true,
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"]
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}
like image 827
WillD Avatar asked Feb 12 '26 04:02

WillD


2 Answers

The Array.prototype.at() method is part of ES2022, which didn't quite make it into TypeScript 4.5. It is part of TypeScript 4.6, so once that is officially released (which, according to microsoft/TypeScript#46858 should be today, 2022-02-22,) you can just set your target to ES2022 or ESNext:

const myArray = [0,4,2]
myArray.at(-1); // okay

Playground link using TS4.6.1-RC

like image 164
jcalz Avatar answered Feb 15 '26 09:02

jcalz


It looks like even specifying "lib": "esnext" doesn't do it (playground).

Temporarily, you can do it manually by using your own definitions file to augment the array interface (as described here):¹

declare interface Array<T> {
   at(index: number): T | undefined;
}

That enables it for now (playground).

In very short order (edit: looks like very short order, see jcalz's answer), you should be able to remove that once TypeScript adds it to the ESNext target (and then to the ES2022 target once the spec is officially adopted in June; the proposal is Stage 4 so it will be in the next snapshot).


¹ There's an argument for index?: number rather than index: number, since the spec explicitly handles the case where converting the argument to number results in NaN by saying to use 0 (at uses ToIntegerOrInfinity on the argument, which does the substitution). So per spec, [10].at() returns 10. But hopefully they use the stricter definition of it.

like image 40
T.J. Crowder Avatar answered Feb 15 '26 09:02

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!