The attribute "at" is not a valid property for an Array

As per the documentation on MDN Web Docs Array.prototype#at method, it should be a valid function. However, when attempting to compile in TypeScript, an error occurs stating that the method does not exist.

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

The console output from tsc shows the issue: https://i.sstatic.net/6ONKS.png

Using bracket notation is not an option as the method needs to handle negative numbers. Adjusting the target setting in the tsconfig.json file to ESNext, ES2021, and ES6 has been tried with no success. The lib option also did not resolve the problem.

json

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

Seeking guidance on resolving this issue. Any help or advice would be greatly appreciated.

Answer №1

As stated on the MDN Web Docs page for Array.prototype#at, this method is considered valid.

It's important to note that MDN's determination of what is part of TypeScript does not hold weight. This decision lies with the TypeScript developers alone.

While MDN's validation may matter to Mozilla, it doesn't impact TypeScript in any way.

Despite this, TypeScript fails to compile the code, claiming the method does not exist.

The reason for this error is that the method is not present in any ECMAScript version supported by TypeScript.

I've attempted various solutions, such as adjusting the target setting in the tsconfig.json file to ESNext, ES2021, and ES6 without success.

This issue arises because the method is absent in both ECMAScript 6 and ECMAScript 2021. It is included in ES2022 (or ESNext), a recent addition after the finalization of TypeScript 4.4 and possibly too late for TypeScript 4.5.

Even utilizing the lib option does not resolve the issue.

Once again, the absence of this method across all library versions supported by TypeScript hinders its usage.

In the current development branch set to become TypeScript 4.6, only features up to ECMAScript 2021 + the latest Internationalization extensions are available in lib/lib.esnext.d.ts.

What steps can be taken? Am I missing something?

Your best course of action is to wait until the method is officially incorporated into a released version of ECMAScript and/or TypeScript.

Answer №2

The method Array#at is a recently introduced feature, accessible only in ESNext or through the utilization of a polyfill. In the case of using the latter option, it is possible to extend the global array interface as demonstrated below:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Data is not defined" error message is triggered when using jQuery DataTable Row Details

While utilizing jQuery Data Tables to construct a datatable with row details, I encountered an error in jquerydatatables.js: data is undefined The JavaScript code being used is: $(document).ready(function() { var dt = $('#tbl_cheque_history' ...

Exploring the potential of Framework7 in Single Page Applications: optimizing performance by preloading

I'm currently working on developing a web application using Framework7. Framework7 offers routing APIs for navigating between HTML pages. It seems that the pages are loaded dynamically through AJAX requests. I am curious if it is possible to preload ...

Develop your own personalized Angular schematics that produces a file that begins with an underscore

Having trouble with custom Angular schematics file naming. I'm trying to create a theme SCSS file that starts with an underscore followed by a double underscore as a delimiter. For instance, I want the file name to be _mouse-theme.scss, using the nam ...

Why do I encounter the issue of receiving a "function not defined" error when using setInterval in conjunction with jQuery?

I need to make updates to a user's field using jQuery. Here is my code snippet... jQuery(document).ready(function(){ setInterval("keepUserActive()", 6000); function keepUserActive() { jQuery.post('/users/update_useractive', ...

Utilize the useTheme type from Emotion Js within ReactJs using Typescript

Greetings! As a newcomer to typescript, I find myself with a query regarding the use of Theme in emotionJs. Here's the snippet of code that has been causing me some trouble: const GlobalStyle: React.FC = (props) => { const Theme = useTheme(); ...

What is the best way to specify a submission destination for a custom form component in Vue?

I am looking to streamline the use of a form component across my website, however, I need the submit button to perform different actions depending on which page calls the form-component. Experimenting with Vue components and data passing is new to me as I ...

Replace jQuery CSS with standard CSS without using !important to override styles

Recently, I encountered a puzzling situation: I have an element with the following CSS properties ($(this) represents the cloned object): clone.css({ 'width': $(this).width() + 'px', 'height': $(this).height() + ' ...

Are there any better methods for transforming a class component into a hook component?

After some attempts, I'm working on getting this code to function properly using useState: https://codesandbox.io/s/rdg-cell-editing-forked-nc7wy?file=/src/index.js:0-1146 Despite my efforts, I encountered an error message that reads as follows: × ...

How can I retrieve the most recent date from a collection of hashes and then extract the corresponding name key/value pair?

I am dealing with an array of hashes structured like this: [ { "Address": 25, "AlertType": 1, "Area": "North", "MeasureDate": "2019-02-01T00:01:01.001Z", "MeasureValue": -1 }, { "Address": 26, "AlertType": 1, "Area": "West", "MeasureDa ...

Release a stationary element upon scrolling down the page

I have a calculator feature on my website which was coded in php. At the end of this calculator, there is a section that displays the results. While the results div works properly on desktop, I am looking to implement a fix for mobile devices. Specificall ...

Choose every fourth row in the table

Is there a way to alternate the background colors of selected groups of 4 rows in a table? I want to make one group red and the next group blue. Any suggestions or ideas on how to achieve this? <table> <tr style="background-color: red;"> ...

Tips for enabling mouse functionality while utilizing PointerLockControls

I'm currently working on a 3D art gallery using Three.js and PointerLockControls for navigation. My goal is to have the artwork on the gallery walls clickable, triggering a pop-up window with additional information. However, it seems that PointerLock ...

Setting the className in Next.js without using {styles.red} can be achieved by directly passing the

Description I'm trying to use just the pure class name without the {styles.class-name} convention in Next.js. After doing some research, I discovered that I need to configure the next.config.js file. Does anyone have good references for this? Current ...

Searching for specific objects within a nested array in TypeScript

I have been searching for examples for a while now, but I haven't found anything similar. My understanding of the filter function is lacking, so any assistance would be greatly appreciated. The goal is to remove elements from the object where the nest ...

What is the method for extracting individual elements from an object returned by a React hook in Typescript?

I am currently working on a component that needs access to the query parameters from React Router. To achieve this, I have been using the use-react-router hook package in my project. This is what I am trying to accomplish: import React from "react; impor ...

Enhancing Images: A guide to updating uploaded images using jQuery File Upload

Currently, I have implemented jQuery File Upload for PHP and it seems to be functioning effectively. However, I am facing a slight issue where if I open two tabs of the same page (index.html) in my browser and upload a photo on tab 1, the uploaded photo is ...

Issues with connecting local CSS and JS files to HTML pages

I am facing an issue with my base HTML file that I want all other pages to inherit certain characteristics from. The problem arises when I try to link an external CSS file like bootstrap.css from within my project directory. I have the file stored in the s ...

The object literal is restricted to defining existing properties, and 'id' is not a recognized property in the type 'FindOptionsWhere<Teacher>'

I encountered a persistent error within my teachers.service: Object literal may only specify known properties, and 'id' does not exist in type 'FindOptionsWhere | FindOptionsWhere[]'.ts(2353) FindOneOptions.d.ts(23, 5): The expected t ...

Guide on integrating a Web Worker included in an NPM module within a NextJS project

If you're experiencing issues, refer to the Github Repository here: https://github.com/kyledecot/next-worker-bug Within my NextJS application, there is an NPM package that I have bundled using webpack/ts-loader. This package includes a web Worker & W ...

How come the Qunit counter doesn't seem to ever reach its expected target value during this test?

I'm currently stuck on a Qunit test related to jQuery Mobile's listview.filter extension. I can't figure out how the variable _refreshCornersCount ends up with a value of 3. Below is the section causing confusion. module( "Custom search ...