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

Securing routes and layouts in the MEAN Stack framework

I am currently utilizing the MEAN Stack framework and have created 3 different layouts. I am looking to secure each layout route to prevent unauthorized access. const routes: Routes = [ { path: '', redirectTo: '/dashboard', ...

Error Encountered: Visual Studio cannot locate the file 'COMPUTE_PATHS_ONLY.ts' during the build process

Upon fixing my visual studio 2015, an error was thrown that I haven't encountered before. Error Build: File 'COMPUTE_PATHS_ONLY.ts' not found. I did not add COMPUTE_PATHS_ONLY.ts to my Git repository. The other files in the repo rema ...

The Typescript error occurs when trying to assign a 'string' type to a 'SetStateAction<null>'

For my project, I am delving into creating a global context using TypeScript. As a newcomer to TypeScript, I found a helpful guide in this blog post (). Despite following the outlined steps, I keep encountering an error message saying "Type 'string&ap ...

Identify when the Vue page changes and execute the appropriate function

Issue with Map Focus Within my application, there are two main tabs - Home and Map. The map functionality is implemented using OpenLayers. When navigating from the Home tab to the Map tab, a specific feature on the map should be focused on. However, if th ...

Don't initialize each variable within the constructor of a class, find a more efficient approach

I have a collection of JavaScript classes representing different models for my database. Each model contains attributes such as name, email, and password. Is there a more efficient way to create a new User instance without manually assigning values to ea ...

encountered an issue when testing a dynamic route in Next.js with postman

I recently created a new API route named route.ts, where I included two different routes. One route retrieves all users from the database, while the other retrieves a specific user based on their ID passed as a query parameter. However, when testing these ...

Exploring the Angular RouterModule within a Java WAR Deployment

In my Angular 6.0.5 application, I leverage Angular's Routing feature to define paths like: http://localhost:8080/area http://localhost:8080/barn http://localhost:8080/tower During development, running the app with ng serve allows me to directly en ...

What sets apart window.location.href from this.router.url?

I'm curious about the various methods of obtaining the current URL in Angular. For instance: this.router.url My main question is: What advantages does using this.router.url offer over simply using window.location? Could someone kindly provide an exp ...

Assigning a specific data type to an object in TypeScript using a switch case statement

I am currently developing a React Native app using TypeScript. As part of my development, I am creating a handler with a switch case structure like the one below: export const handleMessageData = (dispatch: Dispatch, messageData: FCMMessage): void => ...

What is the best way to send a string parameter from an Angular UI to a Node.js backend?

My goal is to transfer a string value from an Angular UI to a Node.js backend API, which will then search in MongoDB using the provided string value as shown below. I am attempting to receive input in enteredValue and pass it on to the http.get call as pa ...

ReactJS Typescript Material UI Modular Dialog Component

Hello, I need help with creating a Reusable Material UI Modal Dialog component. It's supposed to show up whenever I click the button on any component, but for some reason, it's not displaying. Here's the code snippet: *********************TH ...

How come TypeScript tuples support the array.push method?

In the TypeScript code snippet below, I have specified the role to be of Tuple type, meaning only 2 values of a specified type should be allowed in the role array. Despite this, I am still able to push a new item into the array. Why is the TS compiler not ...

Converting constants into JavaScript code

I've been diving into typescript recently and came across a simple code snippet that defines a constant variable and logs it to the console. const versionNuber : number = 1.3; console.log(versionNuber); Upon running the tsc command on the file, I no ...

Having trouble retrieving response headers in Angular 5

After sending a post request to a server, I receive a response with two crucial headers for the client: username and access-token. The Chrome debug tool's Network Tab displays the data from the response like this: In addition, I attempt to log the re ...

Encountering error TS2305 in Visual Studio Code while working with moment.js in an example from an Angular Material

After referencing the code snippet from https://material.angular.io/components/datepicker/overview#choosing-a-date-implementation-and-date-format-settings, I encountered an issue. While the code successfully compiles and runs, Visual Studio Code flagged an ...

Is there a way to access and read an Excel file stored within the assets folder using Angular?

I need assistance converting an excel file to a JSON format. My excel file is currently stored in the assets folder, and I am looking for guidance on how to access it from app.component.ts. Any help would be greatly appreciated! ...

Ways to enforce a specific type based on the provided parameter

Scenario Background: // Code snippet to do validation - not the main focus. type Validate<N, S> = [S] extends [N] ? N : never; // Note that by uncommenting below line, a circular constraint will be introduced when used in validateName(). // type Val ...

Retrieving data through an Angular Material Table by employing an HTTP GET request

I am working with an Angular Material table and need to retrieve data from a service. Below is the code for the service. import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { Message } from '../messag ...

type Y does not contain property X

When I encounter this error message: The property 'module' is missing in the type 'Menu'. The property 'parentId' is not found in the type 'Menu'. the code snippet triggering it appears like this: private menus: ...

Debate surrounding the use of .next() in conjunction with takeUntil

Recently, I've observed a change in behavior after updating my rxjs version. It seems that the .next() method this.ngUnsubscribe$.next(); is no longer functioning as it used to: export class TakeUntilComponent implements OnDestroy { // Our magical o ...