A collection of objects in TypeScript with a reference and the ability to add new objects using the

Recently, I've come across an issue in my code while working with custom objects and arrays of them. I have identified a scenario where the push() method works fine and another where it doesn't.

Scenario 1 (working as expected):

class MyObject{
  private reference: d3.Selection<SVGElement>;

  public constructor(ref: d3.Selection<SVGElement>){
    this.reference = ref;
  }
}

interface ViewModel{
  objects: MyObject[] 
}

class MyApp{
  private root: d3.Selection<SVGElement>

  private viewModel: ViewModel;

  constructor(options: Type){
    this.root = options.root
    this.viewModel.objects.push(new MyObject(this.root))
  }
}

Scenario 2 (not functioning properly):

class MyObject{
  private reference: d3.Selection<SVGElement>;

  public constructor(ref: d3.Selection<SVGElement>){
    this.reference = ref;
  }
}

class MyApp{
  private root: d3.Selection<SVGElement>

  private objects: MyObject[];

  constructor(options: Type){
    this.root = options.root
    this.objects.push(new MyObject(this.root)) //seems to freeze the whole program
  }
}

Could you please point out what I might be doing wrong? Any assistance would be highly appreciated.

Michal

Answer №1

It seems like you haven't set up your objects array yet:

private objects: MyObject[] = [];

Give that a try :)

By the way, in your 'working' example, you also forgot to initialise your viewModel. Did you only share a simplified version of your code?

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

What is the best way to connect the elements in two separate arrays?

I have a scenario with two arrays and a variable: var Names = ['jack', 'peter', 'jack', 'john']; var Ids = ['1' , '2' , '3' , '4' ]; Also, I have this search varia ...

What strategies can be utilized to extract the structure of JSON files imported via a TypeScript asynchronous function?

Examining the example below: export type AppMessages = Awaited<ReturnType<typeof loadMessages>>; export type Locale = "en" | "fr" | "es"; export const loadMessages = async (locale: Locale) => ({ foo: locale ...

Refresh Angular page data following new routing paths

The chat box page in the image below was created using Nebular: Nebular Documentation View Chat Box Photo After clicking on one of the user names (2) from the list, the URL ID (1) changes but the corresponding data does not load. Note: I have created a m ...

Can you provide instructions on executing package dependencies using yarn in the command line? For example, is there a command similar to npx tsc init for initializing a npm

When utilizing yarn, the node_modules folder is not present. Instead, dependencies are stored in a .yarn/cache folder. I attempted to use yarn dlx tsc init and npx tsc init, but they did not achieve the desired result. There are various development depend ...

Issue encountered while iterating over an array using NgFor

I am currently facing an issue while attempting to create a table for viewing certificates in an account using Angular. The error I am encountering is as follows: ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are ...

Ways to verify if a certain type possesses an index signature during runtime

Is it possible to create a type guard in JavaScript that checks if a given type implements an index signature? I'm unsure if this concept would be viable, but here is the idea: I am looking for guidance on how to implement the logic within this funct ...

Restrict results according to values post-merge activity - MongoDB

In my database, I have two collections structured as follows: Collection 1 { "_id": "col1id1", "name": "col1doc1", "properties": [ "<_id1>", "<_id2>", "<_id3>"] } Collection 2 { "_id": "<_id1>", "name": "doc1 ...

Ways to collect particular tokens for delivering targeted push notifications to designated devices

When filtering the user's contacts, I ensure that only contacts with created accounts are displayed on the screen. This process helps in visually organizing the contact list. List<PhonesContacts> phoneContacts = snapshot.data; Lis ...

Attempting to map an object, however it is showing an error stating that the property 'title' does not exist on type 'never'

While attempting to retrieve data from the Bloomberg API, I encountered an issue when trying to extract the title from the response object. The error message received was: Property 'title' does not exist on type 'never'. Below is the co ...

Tips on dynamically looping the formcontrolname and implementing validation strategies

Looking for a way to validate multiple looping of dynamic formControlName="xxx" in select field. Check out my HTML code: <ul *ngFor="let detaillist of stressli.stresstabdetails;"> <li> <div class="form-container"> ...

Merging two arrays of objects from the same response in JavaScript

How can I efficiently merge two arrays of objects from the same response? let data = [{ "testLevel":"mid", "testId":"m-001", "majorCourse": [ { "courseName":"C++" ...

Having an issue where the Material Angular 6 DatePicker is consistently displaying my selected date as one day earlier

I've encountered a strange issue with the current version of the Material Angular DatePicker. After upgrading from A5 to A6, it started to parse my date one day earlier than expected. You can see an example of this problem here: https://stackblitz.com ...

Issue with hydration when logging in with Next-Auth in NextJS 13.4

Step-by-step Instructions: 'node -v' -> v18.16.1 'npx -v' -> 9.8.0 To start, I created a new Next.js app by running npx create-next-app@latest in the terminal within my app folder. Here is a link to the package.json file. Nex ...

Concealing the TinyMce Toolbar upon initialization

After setting my content with tinymce, I want to make the toolbar readonly. To achieve this, I subscribed to the editor's init function like so: editor.on('init', () => { editor.setContent(this.value); if (this.disab ...

An issue occurred while trying to run Ionic serve: [ng] Oops! The Angular Compiler is in need of TypeScript version greater than or equal to 4.4.2 and less than 4.5.0, but it seems that version 4

Issue with running the ionic serve command [ng] Error: The Angular Compiler requires TypeScript >=4.4.2 and <4.5.0 but 4.5.2 was found instead. Attempted to downgrade typescript using: npm install typescript@">=4.4.2 <4.5.0" --save-dev --save- ...

Using a string list to define variable names or object attributes: a guide

My goal is to create an object with attributes based on a list of strings. I've come across suggestions involving dictionaries, but that doesn't seem to be the right approach for my current project. Here's a simplified version: abilities = ...

Using object in Typescript for function overloading - External visibility of implementation signatures for overloads is restricted

Issue How do I correctly expose an overloaded implementation signature? Scenario Expanding on the initial query: interface MyMap<T> { [id: string]: T; } type Options = { asObject?: boolean, other?: Function testing?: number }; function g ...

I need help figuring out how to represent a nested array within an array of objects within my data instance in Vue

Currently, I have a loop that is showcasing a list of items along with their respective sub-items. The data response payload for this operation appears like the following. I have successfully executed the loop and managed to display it on my frontend desi ...

Selecting a random string element from an array using C programming

I'm still learning my way around C, although I'm quite experienced in programming. My current project involves developing a program that prompts for user input and then outputs a predetermined string saved in an array. What I aim to achieve is s ...

Fetching Data from Response Headers in Angular 4.3.3 HttpClient

(Text Editor: Visual Studio Code; TypeScript Version: 2.2.1) The main objective here is to fetch the headers of the response from a request Let's consider a scenario where we make a POST request using HttpClient within a service: import { Injec ...