Typescript's Array extension causes issues with constructors

During my experimentation with TypeScript, I encountered an interesting behavior:

class ExtArray<U> extends Array<U> {

    constructor(...args : U[]) {
        super(...args);
    }

    public contains(element : U) : boolean {
        var i = this.indexOf(element);
        return i !== -1;
    }
}


var test : ExtArray<string> = new ExtArray("a", "b", "c");

test.push("y");

console.log(test.length); // 1

console.log(test[0]);  // y
console.log(test[1]);  // undefined
console.log("Has a: " + test.contains("a"));  // Has a: false
console.log("Has y: " + test.contains("y"));  // Has y : true

The output of the console.log statements has been included as comments above. For an executable example and the JavaScript code, check out this TypeScript playground.

It appears that the elements passed to the constructor are not being added to the array.

The extending expression section in What's New in TypeScript suggests that extending the native Array type like this should be possible in TypeScript 1.6. However, I couldn't find any information in the TypeScript language reference that explains this behavior.

Most of the other questions I found about extending Arrays are dated at least a year old and often refer to pre-1.0 versions of TypeScript, recommending setting up the prototype chain directly.

I am puzzled by what could be going wrong here and I'm beginning to suspect a TypeScript bug or some undocumented restriction for extending Arrays.

Can anyone shed light on what might be going wrong here?

Answer №1

To better comprehend the scenario, consider using JSON.stringify() on your object:

let example : CustomArray<string> = new CustomArray("x", "y", "z");
example.push("w");

// displays {"0":"w","length":1}
document.writeln(JSON.stringify(example)); 

If you create a new instance of a regular Array, the resulting object will appear quite distinct:

let example : Array<string> = new Array("x", "y", "z");
example.push("w");

// displays ["x","y","z","w"]
document.writeln(JSON.stringify(example));

It seems somewhat perplexing that the documentation could convey a different expectation regarding the behavior of the subclass's constructor. Moreover, there are inconsistencies in determining whether the subclass is an Array using the methods outlined in this post:

example.constructor === Array // false
example instanceof Array // true
Array.isArray(example) // false

Consider raising an issue on the TypeScript GitHub repository. Even if this behavior is deliberate, the official documentation should be amended to clearly outline the expected behavior when subclassing native objects.

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

Filtering out duplicate names from an array of objects and then grouping them with separator IDs can be achieved using JavaScript

Imagine we have an array [ {id: 1, label: "Apple"}, {id: 2, label: "Orange"}, {id: 3, label: "Apple"}, {id: 4, label: "Banana"}, {id: 5, label: "Apple"} ] We want the output to be like this [ {id: 1~3~5, l ...

The DataContractJsonSerializer in C# encounters issues when the value can be either an array or a singular item

Using the DataContractJsonSerializer has been helpful in parsing a json string into an object hierarchy. The structure of the json string is as follows: { "groups": [ { "attributes": [ { "sortOrd ...

Practical strategy for developing and launching a TypeScript/Node.js application

I'm currently developing a node.js app using Typescript, which requires compilation to JS before running. As someone with a background in java/jvm, I'm hesitant about the deployment process where code is pushed to git, built/compiled on the serve ...

Interfaces and Accessor Methods

Here is my code snippet: interface ICar { brand():string; brand(brand:string):void; } class Car implements ICar { private _brand: string; get brand():string { return this._brand; } set brand(brand:string) { this. ...

Error: There was a problem trying to import the `.d.ts` file

Software Stack Vue version 3.2.19 @vue/test-utils version 2.0.0-rc.15 Typescript version 4.1.6 Issue Description Encountering an error when running the command vue-cli-service test:unit --no-cache. Please refer to the TypeError screenshot (link to Con ...

Arranging elements within a structured array using the bubble sort algorithm in C++

I am attempting to arrange my Student data type array, named student_database, by its member ID array from lowest to highest using a bubble sort algorithm. I found an example in a C++ textbook and implemented it into my program. Although the code compile ...

Exploring the World of String Arrays in C++

I am working on a project that involves utilizing the string library to allow users to input multiple lines of symbols that I will then flip. Initially, my approach was to use an array of strings for this task. However, despite being confident in my inpu ...

Is it necessary for me to develop an Angular library in order to release a basic TypeScript class that makes use of Angular components?

In one of my Angular projects, I have a Typescript class called APIResponse that I want to convert into an NPM package for use in other projects. This class is not specific to Angular like a Service or Component. After doing some research on creating non-A ...

What is the best way to create unit tests for a React component using TypeScript?

I recently completed a small React project using TypeScript and decided to have it print numbers of li tags in the browser. During this process, I wanted to write unit tests that would test if the component created the HTML element . However, as someone ...

Create dynamic breadcrumb trails using router paths

I am currently working on developing a streamlined breadcrumbs path for my application. My goal is to achieve this with the least amount of code possible. To accomplish this, I have implemented a method of listening to router events and extracting data fr ...

Using TypeScript, the fetch function cannot be assigned

Why am I encountering this TS warning? Type 'unknown' is not assignable to type 'PokemonList'.ts(2322) This issue is on line: "return e" Here is the code snippet: export interface PokemonList { count: number; next: stri ...

Tips for combining two arrays by property value in React using ES6

I am facing a challenge with two arrays: array1 = [{"sourceId": "1", "targetId": "2", "name": "heats air"} , {"sourceId": "3", "targetId": "4", "name": "power"}] array2 = [{"name": "Hair Dryer", "id": "1"}, {"name": "Heating System", "id" ...

The member 'pipe' is not found within the 'AngularFireObject<{}>' type

As someone new to Angular, I've been following a tutorial by Mosh Hamedani on version 6 of Angular, but unfortunately the tutorial is based on version 4. Currently, I'm working on an e-commerce project that involves implementing an AddToCart butt ...

The solution to resolving setState not updating within a react context

I am encountering a problem where my context does not seem to update when I attempt to modify it using a react hook. The code snippet is provided below, and I have a feeling that I might be overlooking something minor. appContext.tsx import React, { use ...

Is it possible to deduce a more precise type from a dictionary in TypeScript? What steps can be taken to assist TypeScript

Behold the incredible code I have: export type Locale = "en" | "fr"; export type Namespace = "products" | "home"; const dict = { en: { home: { title: "My Super Title" }, products: { product: &quo ...

I'm interested in creating a unique form validator in Angular that verifies if a string has a combination of letters and numbers. How can this be

Currently, I am developing a registration form within Angular that mandates users to create a password comprising of both letters and numbers. I am in need of embedding a personalized validator to uphold this regulation. What would be the most practical ap ...

How to declare and initialize a two-dimensional array in Python

When attempting to declare a multidimensional array in Python, I encountered the following issue: Nbrs[23][2] = [[1, 1], [1, 2], [2, 1], [2, 3], [3, 2], [1, 3], [3, 1], [1, 4], [3, 4], [4, 3], [4, 1], [1, 5] ...

What is the mechanism behind the functionality of the .any() method in Python?

Looking to create a script that models the behavior of chemical reactions over time. One key input is an array like this: popul_num = np.array([200, 100, 0, 0]) This array represents the number of molecules for each species within the system. The main fun ...

Unlocking the power of URL manipulation in Fastify using Node.js

I'm attempting to retrieve specific parts of the URL from a Fastify server. For instance, the URL looks like this: http://localhost:300/query_tile/10/544/336 Within the Fastify server, I need the values for z/x/y. I've attempted the following ...

Having trouble getting the onClick function to work in your Next.js/React component?

Recently, I delved into using next-auth for the first time and encountered an issue where my login and logout buttons' onClick functions stopped working when I resumed work on my project the next day. Strangely, nothing is being logged to the console. ...