The properties of the extended Array class in TypeScript are not able to be accessed

It might be the late hour or my brain overloaded with programming, but I'm completely puzzled by this simple class:

export class Path extends Array {
    constructor(...params:Array<any>) {
        super(...Object.assign([], arguments));
    }
    until (node) {
        let pos = this.findIndex(element => node === element);
        return pos < 0 ? [] : this.splice(0, pos + 1);
    }
    get last () {
        return this.length ? this[this.length - 1] : undefined;
    }
}

Although the class initializes fine when called in TypeScript, none of the methods seem to work:

path = new Path(1,2,3,4); // [1,2,3,4]
path.last; // undefined
path.until(3); // undefined

Interestingly, when I create a similar class without extending Array, everything works as expected:

export class Bla {
    values = [];
    constructor(...params:Array<any>) {
        this.values = new Array(...Object.assign([], arguments));
    }
    until (node) {
        let pos = this.values.findIndex(element => node === element);
        return pos < 0 ? [] : this.values.splice(0, pos + 1);
    }
    get last () {
        return this.values.length ? this.values[this.values.length - 1] : undefined;
    }
}

This yields the correct results:

bla = new Bla(1,2,3,4); // {values: [1,2,3,4]}
bla.last; // 4
bla.until(3) // [1,2,3]

To make things even more confusing, if I try the Path class code in the Chrome dev console (excluding the TypeScript typings and export), it works flawlessly:

path = new Path(1,2,3,4); // [1,2,3,4]
path.last; // 4
path.until(3) // [1,2,3]

What am I missing in the enigmatic world of TypeScript?

Answer №1

By simplifying the super call, everything is functioning perfectly for me:

class Route extends Array {
    constructor(...arguments:Array<any>) {
        super(...arguments);
    }
    get final() {        
        return this.length ? this[this.length - 1] : undefined;
    }
}


const route = new Route(5, 4, 3);
console.log(route.final); // 3

https://i.sstatic.net/bJDLk.png

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

The status of the 'slider' may be 'undefined'

I'm really struggling to figure out how to resolve this issue, even though I suspect it's a simple fix that's eluding me... Here is the part of my code in TypeScript that's causing the error: const slideLeft = () => { cons ...

leveraging parcel for importing typescript dependencies

I am currently using parcel to process typescript for a web extension. I have installed JQuery and its type definitions via npm. In my typescript file, I have the following at the top: import $ from "jquery"; import "bootstrap"; However, when running run ...

What is the process for extracting an object from an array?

As a newcomer to jQuery, I've encountered an issue that has me stuck. My problem lies in accessing an array within an object. Here's the structure of my object as shown during debugging: cache:object 0001-:Array[2] 0:value1, ...

Various types of generics within an object

Is there a way to achieve different types for the nested K type within a type like MyType? Here's an example: type Config<K> = { value: K; onUpdate: (value: K) => void; } type MyType<F extends string> = { [K in F]: <V>() =& ...

Experiencing an issue with type error when transitioning syntax from using require to import

After transitioning from require in CommonJS syntax to import in ES Module syntax, I encountered an error. I decided to develop a todo-app using Node.js, TypeScript, and MySQL. To start off, I wrote the initial code snippets below: // db.ts export {}; co ...

Set an array to a JSON object as a fresh entity

My challenge involves working with an array that contains certain values. let myArray = [value1, value2]; I am looking to generate a JSON object in the format shown below: { "field": "[value1, value2]" } ...

AngularJS: Render the initial element of the result set array

Currently, I have a form that consists of two dynamic dropdowns - one for selecting the location and the other for choosing the branch. When a location is selected, the corresponding branches for that location will be automatically displayed in the Branch ...

Constructing an Angular 2 application using a solo TypeScript file that is compiled individually

At the moment, I am in the process of developing a Chrome Extension using Angular 2. The application includes a background.js file which handles the functionality for a long-running task that operates while the extension is active. Currently, this backgrou ...

Encountering the error message "Unable to access properties of null (specifically 'useState')" while trying to utilize a component from my custom library

After developing a personalized UI library and style guide to standardize components in my application, all was running smoothly until I incorporated a component utilizing the useState hook. An error consistently surfaces whenever I attempt to use a compo ...

Is there a way to transform row results into an array similar to array($result)?

I am struggling to add my row result to an array like array($output_variable). Here is what I have tried: <?php require('init.php'); session_start(); $result = mysqli_query($conn, 'SELECT item_name , quantity FROM books WHERE ...

What is the process for transforming a python list containing multiple 3D arrays into a single 3D array with a predefined shape?

I have a list called itemlist containing 25 3D Arrays, each with a shape of (128x128x3). My goal is to combine all these arrays into a single cohesive array, essentially creating an image. I anticipate the new shape to be (640, 640, 3), resulting in 5 row ...

I'm encountering a Typescript error where I'm unable to assign a function to RefObject.current and it's indicating that the function is not callable

Does anyone know why assigning a function type to a ref.current type is causing me issues? useEffect(() => { savedHandler.current = handler; // ERROR HERE: }, [handler]); TS2741: Property 'current' is missing in type '(e: Chang ...

The parameter type cannot be assigned an undefined argument

I am new to TypeScript and trying to check if an item already exists. However, when I define the previous variable, I'm encountering an error: "Argument of type '(prev: CartItemsType[]) => CartItemsType[] | undefined' is not assignable to ...

Deactivate a variable during operation

I have a unique component called book-smart that has the functionality to display either book-update or book-create based on the availability of a BookDto in my book.service. The update feature can be accessed by clicking a button in a table, while the cre ...

How to efficiently eliminate redundant entries from an object array using JavaScript or React

I've been struggling to implement the solutions provided in this thread on removing duplicates from an array of objects. Unfortunately, I haven't found a satisfactory way to do so. In my current approach (which involves adding new iconsProps to ...

Upon updating my application from Angular 14 to 16, I encountered an overwhelming number of errors within the npm packages I had incorporated

After upgrading my angular application from v14 to v16, I encountered numerous peer dependencies issues, which led me to use the --force flag for the upgrade process. However, upon compiling, I am now faced with a multitude of errors as depicted in the scr ...

Retrieve the data in the format of [1,2,3] from a MySQL database by employing PHP and jQuery

I'm currently working on a jQuery code that connects to getdata.php. The val in this code is a dynamic value and the function gets called every time an option is selected from a dropdown. function getMoleculeData(val){ var molval=val; ...

Having trouble retrieving data from a JSON object that has been stringified. This issue is arising in my project that utilizes Quasar

I successfully converted an excel spreadsheet into a JSON object by using the xml2js parseString() method, followed by JSON.stringify to format the result. After reviewing the data in the console, it appears that I should be able to easily iterate through ...

What causes the Cassandra client driver to provide more detailed information compared to cqlsh?

I'm currently utilizing the datastax nodejs-driver to retrieve information about a keyspace from cassandra. const results = await client.execute( ` DESC KEYSPACE ${keyspace} ` ); The method client.execute provides a comprehensive object containin ...

Encountering a problem where I am unable to input text in a textbox after making changes

I'm having trouble editing a text field. I can't seem to type anything when trying to edit. Strangely, everything works fine when adding a user, but the issue only arises during editing. Take a look at my code below - const initialState = { ...