A missing Array.at() method has been reported in TypeScript array type

When I try:

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

I encounter the following error related to .at

The error message reads: Property 'at' does not exist on type 'number[]'.ts (2339)

Why is Array.at() not working in this case? Is there a specific browserlist value that needs to be set in order for TypeScript to recognize and enable this recently specified feature?

Here is more information about Array.at() on MDN.

This is the content of my tsconfig.json file:

{
  "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"]
}

Answer №2

It seems that even when specifying

"lib": "esnext"
, it still doesn't work as expected (check here).

For the time being, you can manually achieve this by creating your own definitions file to enhance the array interface (as detailed here):¹

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

This will make it functional for now (see here).

In a very short amount of time (edit: it appears to be very short, refer to jcalz's answer), you should be able to remove this once TypeScript includes it in the ESNext target (and subsequently in the ES2022 target once the specification is officially adopted in June; since the proposal is currently at Stage 4 it will be implemented in the next snapshot).


¹ There's a case to be made for using index?: number instead of index: number, since the specification explicitly addresses situations where converting the argument to a number results in NaN by recommending the use of 0 (at utilizes ToIntegerOrInfinity on the argument, which substitutes accordingly). Therefore, according to the specification, [10].at() would return 10. Hopefully, they adhere to the stricter definition.

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

Is there a way to switch an element across various pages within Ionic 3?

Is it possible to exchange information between two pages using logic? I have successfully implemented a checklist, but I am unsure how to add a success/error icon next to the Room name on the 'verifyplace.html' page after invoking the goToNextPa ...

Tips for displaying an array of objects in a single <li> tag in React

I have an array with nested arrays structured like this: [Array(2), Array(2), ...] example Each subarray contains two objects with a "text" property. obj = {key: something, text: something} Now I am looking to render the "text" property of each subarra ...

I hope to retrieve a specific string from an array using PHP

Recently, I installed a WordPress plugin that allows me to rearrange posts easily. This particular plugin showcases the post_name within a drag-and-drop box. Now, what I want to achieve is changing the format of the "post_name" to "post_name - custom f ...

Display all items that contain a specified string using JavaScript

I'm in need of some assistance with a problem that I've been struggling with. I have several JavaScript objects containing different data pieces as shown below:- Object {id: 1, shopcounty: "cornwall", shopaddress: "the cycle centre,<br />1 ...

How do I implement a dynamic input field in Angular 9 to retrieve data from a list or array?

I'm looking to extract all the strings from the Assignes array, which is a property of the Atm object, and populate dynamic input fields with each string. Users should be able to update or delete these strings individually. What approach can I take us ...

Unable to bring in a TypeScript library that was downloaded from a GitHub fork repository

Currently, I am working on developing a GitHub app using the probot library. However, I have encountered an obstacle as outlined in this particular issue. It seems that probot does not offer support for ESM modules, which are crucial for my app to function ...

How to resolve the issue of not being able to access functions from inside the timer target function in TypeScript's

I've been attempting to invoke a function from within a timed function called by setInterval(). Here's the snippet of my code: export class SmileyDirective { FillGraphValues() { console.log("The FillGraphValues function works as expect ...

Changes in model not reflected in the view

In my Angular app (5.2.3), I have implemented a feature to display a login/logout button in the top right corner of the page. The functionality involves silently logging the user in using an external Open ID Connect provider and then displaying the user&ap ...

Cross-component communication in Angular

I'm currently developing a web-based application using angular version 6. Within my application, there is a component that contains another component as its child. In the parent component, there is a specific function that I would like to invoke when ...

What could be causing the peculiar behavior I am experiencing when a child component attempts to display values from an object fetched in the parent component?

I am currently developing an Angular application and encountering a challenge when it comes to passing data from a parent component to a child component using the @Input decorator The parent component is named PatientDetailsComponent. Here is the TypeScri ...

Issue with rendering images retrieved from JSON data

Struggling with displaying images in my Ionic and Angular pokedex app. The JSON file data service pulls the image paths, but only displays the file path instead of the actual image. Any ideas on what might be causing this issue? Sample snippet from the JS ...

Guide on integrating Amazon S3 within a NodeJS application

Currently, I am attempting to utilize Amazon S3 for uploading and downloading images and videos within my locally running NodeJS application. However, the abundance of code snippets and various credential management methods available online has left me fee ...

How can a parent component update a child component's prop value in VUE?

I'm facing an issue with managing dynamic props in Vue with TypeScript. Below is my parent component: <script setup lang="ts"> const friends = [ { id: "emanuel", name: "Emanuella e", phone: "08788 ...

Retrieve the unique identifier of a single post from a JSON file within a NuxtJS project

Is there a way to retrieve the unique post id data from a JSON file in NuxtJS? created() { this.fetchProductData() }, methods: { fetchProductData() { const vueInstance = this this.$axios .get(`/json/products.json`) ...

What could be causing my array elements to be printed twice in C#?

I'm having trouble understanding why this code prints the array contents twice. static void Main(string[] args) { Int64 userlength; Int64 userlengthcounter; String unencrypted; char current; start: Console.WriteLine("Please en ...

Implementing ngFor to group values within div containers according to specific keys

In my Angular application, I am working with an array named calendarDates that holds various date-related information. calendarDates = [ {"date": "2018-10-23", "day": 5, "month":10, "year":2018, "price":"500", "date_is_valid": true}, {"date": "2018-10 ...

Incorporating Kekule.js into a TypeScript-based React application

Greetings, community! I've created a React app designed to help individuals in the field of chemistry share their work. To facilitate this, I came across a library called Kekule.js Here is the link Utilizing TypeScript poses a challenge as it requir ...

Developing OnIdle with rxjs

As I explore rxJS, I've come across this code snippet that monitors browser activity such as mouse movements, clicks, and keyboard usage. It's like the opposite of onIdle. import { fromEvent, throttle, debounce, interval, merge } from 'rxjs& ...

Store prefabricated objects in an array

Players in my game will have the ability to choose units from a menu, and then use them in different scenes. To achieve this, I am aiming to store the unit prefabs in a static array using code. I want to then be able to retrieve these prefabs, access thei ...

Fast + Vue3 + VueRouter Lazy Load Routes According to Files

I am currently working on implementing Domain-Driven Design (DDD) to Vue, and the project structure looks like this: src - App - ... - router - index.ts - Dashboard - ... - router - index.ts - ... The goal is for src/App/router/index.ts to ...