Creating an array of objects using Constructors in Typescript

Utilizing TypeScript for coding in Angular2, I am dealing with this object:

export class Vehicle{
    name: String;
    door: {
        position: String;
        id: Number;
    };
}

To initialize the object, I have followed these steps:

constructor() {
    this.door = new Door();
}
export class Door{
    position: String;
    ID: Number
}

Everything works smoothly at this point. However, things get complicated when I attempt to initiate an array of objects.

export class Vehicle{
    name: String;
    door: {
        position: String;
        id: Number;
    };
    color: {
       tone: String;
       shade: String;
    }[]
}

Attempting the same resulted in the following

constructor() {
    for (var i = 0; i < 10; i++) {
        this.color.push(new Paint);
    }
    this.door = new Door();
}


export class Paint{
    tone: String;
    shade: String;
}

The encountered error is as follows:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined TypeError: Cannot read property 'push' of undefined

Answer №1

The issue lies in your declaration of the color property as a tuple with only one item of type {one: string; two: string}

To initialize this tuple, you can do the following:

this.color = [new Color()];

If you prefer to define an array of this type, you can use:

color: {
    one: String;
    two: String;
}[]

and then populate it with an empty array:

this.color = [];
// Add 10 elements to the array, adjusting the number as needed.
for(let i = 0; i < 10; i++) this.color.push(new Color()); 

For further details on tuples, check out the documentation here

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

Handling type errors with React Typescript MuiAccordion OnChange event handler

I'm a beginner in typescript and seeking advice on defining the type for an event handler. I have a component that utilizes material ui Accordion and triggers the handler from a container. Therefore, I need to specify the type of handleChange in my co ...

What would be a colloquial method to retrieve the ultimate result from the iterator function?

I've got a rather complex function that describes an iterative process. It goes something like this (I have lots of code not relevant to the question): function* functionName( config: Config, poolSize: number ): Generator<[State, Step], boo ...

Creating a sidebar in Jupyter Lab for enhanced development features

Hi there! Recently, I've been working on putting together a custom sidebar. During my research, I stumbled upon the code snippet below which supposedly helps in creating a simple sidebar. Unfortunately, I am facing some issues with it and would greatl ...

Steps for creating a copy of an Angular component

https://i.stack.imgur.com/4RMsR.png Whenever the user clicks on the Create Copy button, I aim to replicate the content of the DashboardComponent and position the duplicated version below the original one (the DashboardComponent featuring four dark blue sq ...

Angular-powered dynamic data table component fails to render data sources in display

Currently, I am deep in the process of mastering Angular. I've been developing a versatile table component that can be utilized across my entire application. I have successfully configured the columns and pagination settings. Everything looks correct ...

I thought enabling CORS would solve the issue, but it seems like the restrictions

This is my setup for an asp.net core web API: public void ConfigureServices(IServiceCollection services) { services.AddCors(o => o.AddPolicy("CorsPolicy", builder => { builder ...

Strategies for steering clear of god components in Angular

Currently, I am delving into Angular and following the traditional approach of separating the template, styles, and component into 3 distinct files. The component file houses various functions that serve different purposes: Some functions are activated b ...

Interested in discovering the ins and outs of the JavaScript Map function?

Currently, I am delving into this JavaScript function: function solution (array, commands) { return commands.map (v => { return array.slice(v[0] -1, v[1]).sort((a, b) => a - b).slice(v[2] -1, v[2])[0]; }); } I am puzzled about th ...

There was an unhandled exception that occurred due to a missing file or directory with the lstat error on 'D:a1s ode_modulesquill'

ngx-quill is causing issues in production, any suggestions? I am currently using "ngx-quill": "^13.4.0", but it is unable to find Quill on my server even though it works locally. The problem persists in the pipeline... An unhandled exception has occurred ...

I encountered an issue in my Angular application where I continually receive the error message stating "Module 'fs' cannot be found."

Within my service file, I have imported four crucial libraries: import * as async from "async"; import * as officegen from "officegen"; import * as path from "path"; import * as fs from "fs"; All seems to be functioning well with async, officegen, and pa ...

`Warning: The alert function is not working properly in the console error

I am currently working on integrating otp functionality into my Ionic 3 project. I am facing an issue where I am able to receive the otp, but it is not redirecting to the otp receive page due to a specific error. Below is the console error that I am encou ...

What is the process of transforming a basic JavaScript function into a TypeScript function?

As a Java developer diving into TypeScript for frontend development, I've encountered a simple JavaScript code snippet that I'd like to convert to TypeScript. The original JavaScript code is: let numbers = [123, 234, 345, 456, 567]; let names = ...

How can I extract an object from an array by using a string key in either Observable or lodash?

How can I retrieve a specific object (show) from Shows based on its id being a string in a given sample? I am transforming the result into an RXJS Observable, so using functionalities from RXJS or lodash would be greatly appreciated. //JSON RETURNED with ...

Getting the Class name in Typescript

How can you retrieve the class name from within a Class in typescript? For instance, consider this code snippet: export class SomeRandomName extends AbstractSomething<SomeType> implements OnDestroy { className = 'SomeRandomName'; Is th ...

A function's behavior will vary depending on whether it is a property of an object or not

I've been observing some peculiar behavior: In a typical scenario, TypeScript usually raises an error when an object contains too many keys, like this: type Foo = { a: string; } const a: Foo = { a: "hello", b: "foo" // Ob ...

Challenge with Routing in Angular 2

I'm dealing with a route setup like this: path: 'something/:id/somethingElse' In my header.component.html, I need to include a link to this page. I tried the following approach: <a routerLink="['something',myIdThatIsDynamicO ...

Is there a way to automatically close a p-dropdown when a p-dialog is closed?

One issue I have encountered with my angular component, which includes ngprime p-dialog, is that the p-dropdown within the dialog does not close properly when the user accidentally clicks on closing the dialog. This results in the dropdown options remainin ...

Using Angular to pass an index to a pipe function

Currently, I am attempting to incorporate the *ngFor index into my pipe in the following manner: <td *ngFor="let course of courses | matchesTime:time | matchesWeekday:i ; index as i">{{course.courseName}}</td> This is how my pipe is structure ...

Is there a way to set the submitted variable to true when the form group is submitted, then revert it to false when the user makes changes to the form?

With just one FormGroup, I ensure that when a user submits the form with errors the 'submitted' variable is set to true, displaying the errors. However, my challenge now is how to reset this variable to false when the user makes any changes after ...

Ensuring Proper Angular Deployment of Assets Path

Develop the project using Angular7. Once built using the command ng-build --prod --base-href /client/product/v2/ Deploy it in a vs folder, following this structure: www.domain.com/client/product/vs All images are located in the assets folder, which i ...