Utilizing Array Notation in Typescript to Retrieve Elements from Class

In my programming project, I am working with two classes: Candles and Candle. The Candles class includes a property called list, which is an array containing instances of the Candle class.

class Candles
{
  public list: Array<Candle>;
}

class Candle
{
  public date: number;
  public high: number;
  public low: number;
  public open: number;
  public close: number;
  public volume: number;
}

I aim to encapsulate the list property within the Candles class. For instance,

const candles = new Candles();
candles[3] === candles.list[3];

My goal is for candles[3] to refer to candles.list[3]

Additionally, I want to utilize the map function. Here's an example:

candles.map(function(candle: Candle) {
    console.log(candle.high);
});

Answer №1

To manipulate and redirect calls to an internal list using ES6, you can utilize the Proxy feature:

class Books {
  public shelf: Book[] = [];

  constructor() {
    return new Proxy(this, {
      get(target, propertyKey) {
        console.log('retrieving ', propertyKey);
        if (propertyKey in target) {
          console.log('own property');
          return target[propertyKey]
        }

        console.log('redirecting to inner list');
        const property = target.shelf[propertyKey];
        if (typeof property === "function") {
          return property.bind(target.shelf);
        }

        return property;
      }
    });
  }
}

To indicate that Books can act like an Array, include this declaration:

interface Books extends Array<Book> { }

Now, all array operations (e.g. push, foreach, map...) can be executed on Books:

const books = new Books();
books.push({ title: 'Sample' } as Book);

console.log(books[0] === books.shelf[0]); //true
books.forEach(b => console.log(b));

Try it out with our online demo.

Answer №2

Modifying the indexing functionality in Typescript is not possible since Javascript does not offer this capability either. However, a workaround would be to define a custom type that extends the base array structure, as outlined in this post

Answer №4

My approach was as follows:

class Candles extends Array<Candle>
{
  constructor(candles: Array<Candle.Data>) {
    super(...candles.map((candle) => new Candle(candle as Candle.Data)));
    Object.setPrototypeOf(Candles, Object.assign(Array.prototype, Candles.prototype));
  }
}

In my solution, I eliminated the use of list and opted to simply extend Array<Candle>. Additionally, I included

Object.setPrototypeOf(Candles, Object.assign(Array.prototype, Candles.prototype));
to incorporate both Array methods and custom methods from Candles.

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

Dealing with Dependency Injection Problem in Angular 6

I am grappling with a challenge in my cross-platform Angular application. The crux of the issue is determining the platform on which the app is running and accordingly injecting services. Below is how I've structured it: @NgModule({ providers: [ ...

Issue stemming from reactivity causing difficulties with Vuex data mutation within actions

I have a Vuex store action that needs to interact with the API using new data for updating purposes. My goal is to create a separate object that mirrors an existing value in the store, allowing me to manipulate it without affecting reactivity. However, w ...

Steps for displaying detailed information about a single product on an Ecommerce page

Currently in the process of developing my Ecommerce project, I have successfully created a product grid with links to each specific product. However, I am facing an issue where I am unable to view the data of each individual item. Below is the code for my ...

Mapping a list of records by a nested attribute using Typescript generic types

In my current project, I am implementing a unique custom type called "RecordsByType", which is currently undefined in the code snippet below. Within this snippet, I have various types that represent database records, each with its type defined within a ne ...

The 'posts' binding element is assumed to have a type of 'any' by default

Currently, I'm working on a code project that involves graphql, react, and typescript. In the middle of the process, I encountered an error message stating "Binding element 'posts' implicitly has an 'any' type." I am unsure about w ...

Utilizing a TypeScript function to trigger an action from within a Chart.js option callback

Currently, I am utilizing a wrapper for Chart.js that enables an animation callback to signify when the chart has finished drawing. The chart options in my code are set up like this: public chartOptions: any = { animation: { duration: 2000, ...

Why do I keep being told that the property doesn't exist?

I have the following code in one file: function test<T extends {}>(arg:T):any { return arg.name } In another file, I have this code: interface IItem { name: string } console.log(test<IItem>({name:'3'})) When I try to access ...

The Electron/React/Typescript module is missing: Error: Unable to locate 'fs' in the /node_modules/electron directory

Within my Electron application, I have a file named App.ts. It contains the following code snippet: import { ipcRenderer } from 'electron'; // remaining code However, during the app development process, I encountered this error message: Error: ...

Next.JS-13 has encountered an inappropriate middleware in its App Based Routing functionality

I am currently working on developing a user authentication system that includes features for Login, Signup, and Logout. As part of this project, I have created a middleware.ts file in the src directory, which is located next to the app directory. Below is ...

Numerous mistakes detected in the TypeScript code

I've implemented the following class within an ASP.NET Core React application: import * as React from 'react'; interface MyInputProps { inputType: string; id: string; className: string; parentFunctio ...

Is it beneficial to disable and deactivate Validators in Angular?

Within our Angular framework, we've implemented a form with 10 fields. However, a new requirement has surfaced where certain individuals only require access to specific fields out of the existing 10. To accommodate this, our team is currently addressi ...

Guide on setting up a route in Next.js

Recently, I developed a simple feature that enables users to switch between languages on a webpage by adding the language code directly after the URL - i18n-next. Here's a snippet of how it functions: const [languages, ] = React.useState([{ langua ...

retrieve the state property from NavLink

I am encountering an issue with passing objects through components in my project. Specifically, I have a chat object within a component that defines a NavLink. When a user clicks on the ChatsElement, which is a link, the page navigates to the URL /friends/ ...

Removing spaces within brackets on dynamic properties for objects can be achieved by utilizing various methods such as

I've encountered an issue with my code that involves getting spaces within square brackets for the dynamic properties of an object. Even after searching through Code Style/Typescript/Spaces, I couldn't find any settings to adjust this. Could thes ...

When the appdir is utilized, the subsequent export process encounters a failure with the error message "PageNotFoundError: Module for page /(...) not

I have implemented NextJS with the experimental appDir flag and organized my pages in the following manner: https://i.stack.imgur.com/M7r0k.png My layout.tsx file at the root and onboard look like this: export default function DefaultLayout({ children }) ...

Encountering a SonarQube error message stating "Unnecessary 'undefined' should be removed" when using "undefined" as a function argument

When calling a function, I have been passing "undefined" multiple times as a parameter. However, the SonarQube report is flagging an error stating "Remove this redundant undefined". https://i.stack.imgur.com/YhOZW.png It should be noted that the function ...

Encountering an issue with PrimeNG's <p-calendar> component: the error message "date

I encountered an issue resulting in the following error message: core.es5.js:1020 ERROR Error: Uncaught (in promise): TypeError: date.getMonth is not a function TypeError: date.getMonth is not a function This error occurs whenever I attempt to implement ...

Determine the type of a nested class within TypeScript

Utilizing nested classes in TypeScript is achieved through the following code snippet: class Parent { private secret = 'this is secret' static Child = class { public readSecret(parent: Parent) { return parent.secret } } } ...

Looking for a button that can be toggled on and off depending on the input fields

Even after adding useEffect to my code, the button component remains disabled unless the input fields are filled. It never enables even after that. export default function Page() { const [newPassword, setNewPassword] = useState(''); const [conf ...

It seems that the Angular2-google-maps library is having trouble with installation

Attempting to install the angular2-google-maps library is resulting in errors. The desired library can be found at: The specific error encountered is displayed here: https://i.stack.imgur.com/L2vOY.png Any assistance with this issue would be greatly app ...