Issue: TypeScript is throwing an error of type TypeError because it is unable to read the property "push" of an undefined

I am encountering a common issue while working with TypeScript. The error message I am receiving is:

ERROR TypeError: Cannot read property 'push' of undefined

In my code, I have defined a model called EmailModel:

export class EmailModel {

    public name: String;
    public lastname: String;
    public address: String;
    public company: String;
    public zipcode: number;
    public city: String;
    public phonenumber: number;
    public email: String;
    public product: Array<ProductModelOrder>=[];

    constructor(name: String, lastname: String, address: String, company: String, zipcode: number, city: String, phonenumber: number, email: String,product: Array<ProductModelOrder>=[]) {
        this.name = name;
        this.lastname = lastname;
        this.address = address;
        this.company = company;
        this.zipcode = zipcode;
        this.city = city;
        this.phonenumber = phonenumber;
        this.email = email;
        this.product = product;
    }
}

Furthermore, I have defined a product array in the model:

export class ProductModelOrder {
    public name: String;
    public number: number;
    public pricePerProduct:number;
    public price:number;
}

My intention is to assign values from productOrder to emailModel using the following logic:

for (let prod of this.productCarts){
      this.productOrder.name = prod.product_name;
      this.productOrder.number = prod.numberOfProduct;
      this.productOrder.pricePerProduct = prod.product_price;  
      this.productOrder.price = this.priceForAllProducts; 
      this.emailModel.product.push(this.productOrder);
    }

Despite my efforts, I am encountering an error.

Answer №1

It was mentioned that the

emailModel = <EmailModel>{};
, resulting in the product property being undefined. When you try to
this.emailModel.product.push(this.productOrder);
, it causes an error.

Instead, you should initialize the EmailModel like this:

emailModel = new EmailModel(...params here);

Another approach is:

export class EmailModel {
    public name: String;
    public lastname: String;
    public address: String;
    public company: String;
    public zipcode: number;
    public city: String;
    public phonenumber: number;
    public email: String;
    public product: Array<ProductModelOrder>=[];

    constructor(params: EmailModel) {
       Object.assign(this, params);
    }
}

Then initialize the emailModel like this:

emailModel = new EmailModel({...params here});

Here's a simple example:

export class Person {
   name: string;
   phones: Array<string>;
   age?:number; //optional

   constrcutor(params: Person) {
     Object.assign(this, params);
   }
}

const p = new Person({name: 'Reza', phones: ['6583992']})

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

Enhance tns-platform-declarations with NativeScript

I am working on a NativeScript project and I am trying to incorporate the RecyclerView from Android Support Library. I have added the dependency in the app/App_Resources/Android/app.gradle file: // Uncomment to add recyclerview-v7 dependency dependencies ...

Discovering the worth of objects in a MongoDB array - a guide

I need assistance to access the value of a nested object within an array. I have the _id of the parent object and the _id of the child object in the array, but I am struggling to get the value of "solvedOn" in order to toggle a checkbox behavior. Here is ...

Leveraging a React hook within a Next.js API route

I am looking for a way to expose the data fetched by a React.js hook as a REST endpoint using Next.js. To create a REST endpoint in Next.js, I can easily use the code below in pages/api/index.tsx export default function handler(req: NextApiRequest, res: N ...

What could be the reason for my button not activating my JavaScript function?

I am encountering an issue with my form-validation sample. When I click the submit button, it should display an alert message but it is not working as expected. Here is a link to my sample: sample link I would greatly appreciate any assistance in res ...

Tips on adding an item to an array with React hooks and TypeScript

I'm a beginner with a simple question, so please bear with me. I'm trying to understand how to add an Object to the state array when a form is submitted. Thank you for your help! interface newList { name: string; } const ListAdder = () => { ...

Inheriting static attributes in Typescript without using the static keyword

My project involves utilizing multiple classes that represent entities from a database. abstract class Entity { static columns: Column[]; static showInNav: boolean; static dependencies: string[]; // non-static fields } class Entity_A exten ...

How can we verify that console.log has been called with a specific subset of expected values using Jest?

I am currently experimenting with a function that adds logging and timing functionality to any function passed to it. However, I am facing a challenge when trying to test the timing aspect of it. Here are my functions: //utils.js export const util_sum = ( ...

How to combine PHP array elements into a cohesive string output

After loading an array in the following manner: foreach ($_SESSION['cart'] as $item) { $pid = $item['itemId']; $q = $item['qty']; $orderedItems[]=array('itemId'=>$pid,'qty'=>$q); } I am now ...

Ways to verify if the current date exists within a TypeScript date array

I am trying to find a way in typescript to check if the current date is included in a given array of dates. However, even after using the code below, it still returns false even when the current date should be present within the array. Can anyone please pr ...

Eliminating repetitions from a pair of strings separated by commas

Looking for an efficient way to compare two comma-separated strings and remove duplicates completely. The goal is to eliminate any duplicate items that exist in both strings. For instance, when comparing cat,dog,alligator with alligator,parakeet, the desi ...

What is the best way to display a Nested JSON structure without an object key?

Need help with extracting data from two different JSON structures. The first one is straightforward, but the second is nested in multiple arrays. How can I access the content? See below for the code snippets: // First JSON { "allSuSa": [ { ...

Struggling to figure out how to change the display when navigating between different routes

I've been struggling for the past 3 hours trying to switch between routes. Let me explain further: Server Template HTML: <!-- I want the first div to display when the component opens, but disappear and show router-outlet when a button is clicked. ...

When working with Express router callbacks, the Array.includes() method will always return false, the Array.indexOf() method will always return -1, and

After utilizing fs.readFile() and fs.readFileSync() functions to access the content of 'words_alpha.txt', I discovered that the file can be accessed publicly from this link: https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha. ...

Exploring the NextPage type in Next.js

Could someone provide an explanation of the NextPage type within a Next.js TypeScript project? Most sources mention that it is used for type assignment in Next.js, but I am curious about its practical purpose. When and why should we utilize this type? Wha ...

Oops! Looks like there was an issue with assigning to a reference or variable: Error: Uncaught (in promise)

I seem to be struggling with an issue that I believe may have been addressed before, but after reviewing other solutions, I am unable to pinpoint the error in my code. Any assistance in identifying my mistake would be greatly appreciated. <div class="j ...

When utilizing *NgIf, the button will be shown without the accompanying text being displayed

When trying to display either a confirm or cancel button based on a boolean set in my component.ts, I implemented the following code in my HTML: <mat-dialog-actions class="dialog-actions"> <button class="cancel-btn" ...

Guide to making a personalized decorator in loopback4

async verifyUserMembership(userId: string, productId: string) { if (userId && productId) { const userExists = await Product.find({ where: { userId: userId, id: productId } }); return !!userExists; } return false; } I am ...

Developing mongoose models using TypeScript for subdocuments

Exploring the integration of mongoose models with typescript, following a guide available at: https://github.com/Appsilon/styleguide/wiki/mongoose-typescript-models. Unsure how arrays of subdocuments align with this setup. For instance, consider the model ...

Error encountered during Angular ahead-of-time (AOT) compilation: Internal state issue - Summaries cannot contain members in StaticSymbols

Our team is currently working on implementing ahead of time (AOT) compilation for our Angular 2 project, but we have encountered an error: Error: Internal state: StaticSymbols in summaries can't have members! {"filePath":"C:/Users/bhavy/Documents/p ...

Retrieve the data in the format of [1,2,3] from a MySQL database by employing PHP and jQuery

I'm currently working on a jQuery code that connects to getdata.php. The val in this code is a dynamic value and the function gets called every time an option is selected from a dropdown. function getMoleculeData(val){ var molval=val; ...