Expanding the capabilities of arrays in TypeScript

What could be the issue with my code below?

I've attempted to extend the Array object in my class called MyNumberList. However, when I try to add items to the list, nothing seems to be happening. When I try to access the elements in the list, I only get undefined.

By the way, I'm using TypeScript version 1.8.2.

class MyNumberList extends Array<number> {

  constructor(...numbers: number[]) {
    // It seems like this part is not functioning as expected
    super(...numbers);
  }
}

let numbersList: MyNumberList = new MyNumberList(10, 20, 30);

console.log(numbersList[0]);       // Outputs undefined
console.log(numbersList.length);   // Outputs 0
>

Answer №1

ES5 does not allow for the extension of arrays, causing issues with the code generated by the TypeScript compiler. The constructor code produced looks like this:

function MyNumberList() {
    var numbers = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        numbers[_i - 0] = arguments[_i];
    }
    _super.apply(this, numbers);
}

In this code snippet, _super refers to Array. Normally, _super.apply(this, numbers) would function correctly. However, when it comes to the Array function being called as a function rather than a constructor, there are discrepancies in behavior. This issue is also present in Babel and other ES2015 (ES6) to ES5 transpilers. To properly inherit from an array requires functionalities that are absent in ES5 engines.

To resolve this, modify your constructor code to:

constructor(...numbers: number[]) {
  super();
  this.push(...numbers);
}

By making this adjustment, your instance will be populated correctly. Please note that there may still be limitations on how other Array features will operate.

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

jQuery wrapAll issue

I have a repeating group of three divs in my code that I need to wrap together. Here's an example from my HTML: <div class="one" /> <div class="two" /> <div class="three" /> <div class="one" /> <div class="two" /> <d ...

The image on my aspx page is not showing up after attaching a master page. Could the issue be something other than the ID not being changed?

I implemented the following code to remove the system-generated ID:- Banner.ascx.cs protected override void Render(System.Web.UI.HtmlTextWriter writer) { StringWriter Html = new StringWriter(); HtmlTextWriter Render = new HtmlTextWriter(Html); ...

"Utilize jQuery to load a file when hovering over a specific

How can I dynamically load an external file using jQuery when a user hovers over a specific div? I attempted to load the file like a CSS file on hover but was unsuccessful. Is it possible to load a CSS file on hover as I've seen in some examples? $(d ...

Incorporating a dynamic Sublime HTML5 Video player into your website

Struggling to dynamically load a series of sublime videos on my website, I'm facing issues distinguishing between the 'sublime' and 'sublimevideo' objects. Unfortunately, the documentation isn't offering much help. Here' ...

Retrieving Form Validation Error Value in AngularJS

Incorporating AngularJS 1.2 RC2 and utilizing Bootstrap for CSS, I have constructed a straightforward form as shown below: <form class="form-horizontal" name="form" novalidate> <label class="col-lg-2 control-label" for="name">Name</labe ...

convert the elements of an arraylist into a string array

I currently have an arraylist that may be of varying sizes, including 0. I am looking for a way to convert everything inside the arraylist into a string list. For example, if the arraylist contains 10 elements and I only need the first 5. Is there a more e ...

Ways to implement immutability for objects in Java

This is the code snippet I am working with: final int[] a = new int[5]; a[0] = 10; a[0] = 5; The code above is valid since I am modifying the values within the object and not the reference itself. However, now I want to achieve something like this: int[ ...

Protected hyperlink for the landing page

Prior to redirecting a user to the actual URL when they click on a link, I would like to first direct them to a landing page. <a href="contents/landing_location.php?locationed='.$obj->id.'"> Upon clicking the link, users will be taken ...

"Enhance Your Website's User Experience with jQuery Aut

One of the challenges I am facing involves an Ajax call that retrieves a JSON representation of data created using PHP's json_encode method: ["Montérégie","Montréal - North Shore","Montréal - South Shore"] These values are extracted from a &apos ...

Guide to showcasing object characteristics inside an object in Angular2

My USAFacts object contains properties like StateName, as well as objects like State-Bird which hold information about the state bird. If written in JSON, a record of USAFacts would appear as follows: {"StateName": "PA", "State-Bird": [ { "Name": "Ruffed ...

Ways to display or hide particular div in a table

Coding Example:- '<td>' + item.Message + ' <input type="button" class="btn btn-info" id="' + item.LogID + '" onclick="Clicked(this);" value="View More" /> <p> ' + item.FormattedMessage + ' </p>& ...

Using Plotly.js to generate a visually stunning stacked and grouped bar chart

Is there a way to generate a bar chart on Plotly.js that features both grouped and stacked bars? Ideally, I am looking for a structure similar to the one shown here: Barchart with stacked and grouped charts ...

Running Protractor in Components: A Comprehensive Guide

Protractor is commonly known as a testing framework, and I am currently utilizing Angular 2 for my application. I am interested in incorporating it into my app components, such as launching a browser when a button is clicked. Could you provide guidance o ...

JavaScript ES5 allows for the choice between updating a value or pushing to an array

I've been attempting to add an object to an array of objects only if that specific object is not already in the array. If it is present, the object should be updated instead. My requirement is to achieve this using es5. Below is my current approach: ...

Randomly rearranging a list of names to generate a new list organized according to two specific criteria

Here is a list of names: $names = array( "Alberto", "Bianca", "Claudio", "Douglas", "Erica" ); I want to randomly sort this list to create a mapping like so: $mapping = array( ...

Revise the "Add to Cart" button (form) to make selecting a variant mandatory

At our store, we've noticed that customers often forget to select a size or version before clicking "Add to Cart" on product pages, leading to cart abandonment. We want to add code that prevents the button from working unless a variant has been chosen ...

Is there a method to customize the scrolling speed of VueRouter?

How can I implement smooth scrolling for router links using VueRouter? <router-link :to="{ hash: 'home' }">Home</router-link> <router-link :to="{ hash: 'about' }">About</router-link> Here ...

Angular progress tracker with stages

I have been exploring ways to create a progress bar with steps in Angular 12 that advances based on the percentage of progress rather than just moving directly from one step to another. This is specifically for displaying membership levels and indicating h ...

What is the best way to handle a global path parameter in a Nest.js application?

Currently, I am in the process of constructing a rest API for a fully multi-tenant system using a single database and application. To achieve this, I have chosen NestJS as my framework of choice. My goal is to structure all modules based on the :tenantID t ...

Invoking functions on an array results in the program terminating

Could someone please help me with a Game of Life program in C? I am trying to implement it in the console where the 'field' parameters can be initialized in the main menu. Once everything is set, the drawing starts and we go back to the main menu ...