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

Using TypeScript arrow functions to define parameters

When setting "noImplicitAny": true in TypeScript, you may encounter the following errors: Parameter 'x' implicitly has an 'any' type This error can occur with the code snippet: .do(x => console.log(x)); Another error you might s ...

Dynamic rows in an Angular 2 Material data table

I'm currently working on dynamically adding rows to an Angular 2 Data Table ( https://material.angular.io/components/table/overview) by utilizing a service called "ListService". This service provides me with the columns ("meta.attributes") to be displ ...

Passing the array as query parameters and retrieving it using the angular getAll function is the most efficient way

When using this function, I extract the ids of items and aim to send them as an array for retrieval with getAll(). const queryParams: Record<string, string[]> = selectedItems.reduce( (acc, curr, index) => ({ ...acc, [&apo ...

Why isn't the page showing up on my nextjs site?

I've encountered an issue while developing a web app using nextjs. The sign_up component in the pages directory is not rendering and shows up as a blank page. After investigating with Chrome extension, I found this warning message: Unhandled Runtime ...

Oops! The type error is indicating that you tried to pass 'undefined' where a stream was required. Make sure to provide an Observable, Promise, Array, or Iterable when working with Angular Services

I've developed various services to interact with different APIs. The post services seem to be functioning, but an error keeps popping up: ERROR TypeError: You provided 'undefined' where a stream was expected. Options include Observable, ...

Dealing with the error "Type 'date[]' is not assignable to type '[date?, date?]' in a React hook

I'm attempting to assign a date range but encountering an error that states: Type 'Date[]' is not assignable to type '[Date?, Date?]'. Types of property 'length' are incompatible. Type 'number' is not assignab ...

What is the best way to implement a scroll event in a React application?

Can someone provide guidance on how to properly write the scrollHandler function for this scenario? ` useEffect(() => { document.addEventListener('submit', scrollHandler); return () => document.removeEventListener('scroll', ...

Is there a way to override the JSON.stringify method within the JSON class of a TypeScript project without using a custom call?

Dealing with a React Native and TypeScript app here. I keep encountering an error from Fabric every week: "JSON.stringify cannot serialize cyclic structures." The frustrating part is that the error seems to pop up randomly, without any specific scenario tr ...

What is the best way to filter and sort a nested tree Array in javascript?

Looking to filter and sort a nested tree object for a menu If the status for sorting and filtering is true, how do I proceed? const items = [{ name: "a1", id: 1, sort: 1, status: true, children: [{ name: "a2", id: 2, ...

What is the best way to sequentially invoke methods in Angular?

When initializing in the ngOnInit() method, I need to call several methods synchronously. However, all these methods involve asynchronous calls to an API. The challenge is that certain variables must be set before proceeding with the subsequent methods. Un ...

Modify every audio mixer for Windows

Currently working on developing software for Windows using typescript. Looking to modify the audio being played on Windows by utilizing the mixer for individual applications similar to the built-in Windows audio mixer. Came across a plugin called win-audi ...

Is it possible to use string indexes with jQuery each method in Typescript?

When running a jQuery loop in Typescript, I encountered an issue where the index was being reported as a string. $.each(locations, (index, marker) => { if(this.options && this.options.bounds_marker_limit) { if(index <= (this.opt ...

Using TypeScript and Angular to remove properties from an object

My RandomValue class and WeatherForecast class are causing me some trouble. The WeatherForecast class is functioning properly, populating the table with data as expected. However, the RandomValues class/interface appears to be returning a list of objects w ...

Checking JavaScript files with TSLint

After spending many hours attempting to make this work, I still haven't had any success... I am wondering: How can I utilize TSLint for a .js file? The reason behind this is my effort to create the best possible IDE for developing numerous JavaScrip ...

Struggling with sluggish performance on a certain project within VS Code

My experience with VS code has been excellent over the years, but I recently encountered a problem in one of my projects that caused a significant slowdown in performance. Strangely, other projects are working fine without any issues on VS code. I suspect ...

What are the conditions for Jasmine's .toHaveBeenCalledWith to match the parameters?

I'm working on an Angular service along with its Jasmine test. The test is calling f1() and spying on f2(). The function f2 takes a variable v2 and updates it by setting field 'a' to 3. I expected the function f2 to be called with v2 (as def ...

Patiently waiting for the component variable to be assigned through subscription

I am facing an issue with two calls in my component. The second call depends on the result from the first call. In the first call, I set the value for my component variable "locked". The second call should only be executed when the result is true, meaning ...

Why isn't my Enum functioning properly to display the colored background?

Why isn't the Background Color showing up when I pass in the BGColor Prop dynamically in my next.js + Tailwind app? I have tried passing in the prop for my component, but the color is not appearing. <Title title='This is HOME' descripti ...

Modules cannot be compiled using the 'outFile' option unless the '--module' flag is set to 'amd' or 'system'

I am currently developing a Node-Mongodb server with Typescript and encountered this error during the build process: [14:57:05] Using gulpfile ~/Desktop/mean/gulpfile.js [14:57:05] Starting 'default'... [14:57:05] Finished 'default' af ...

Error: Type '() => () => Promise<void>' is not compatible with type 'EffectCallback'

Here is the code that I'm currently working with: useEffect(() => { document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)'; window.$crisp.push(['do', 'ch ...