What is the best way to add elements to a custom-defined array?

I am currently utilizing Angular 5 with typescript version 2.7.1. Within typescript, I have created a custom type:

 arr: {id: string; name: string; }[];

I am attempting to add an element to the array and have experimented with the following methods:

this.arr.push({id: "text", name: "text"})

However, I encountered the following error: TypeError: Cannot read property 'push' of undefined

let array2 : {id: "id", name: "name"}
this.arr.push(array2)

Again, I received the same error message: TypeError: Cannot read property 'push' of undefined

I am puzzled as to why this is not functioning as expected. I am clearly defining id and name within the push operation. Can anyone provide insight into what I might be missing?

Answer №1

Before utilizing the field, make sure to initialize the array as empty:

this.items = [];

Alternatively, you can initialize it upon declaration:

items: {id: number; title: string; }[] = [];

Answer №2

When I came across this issue, it wasn't immediately obvious that the array needed to be initialized. Once you do that, the array can start accepting objects of its type:

    type person = {id: string, name: string}
    
    const peopleList: person[] =[];
    const newPerson: person = {id: "123", name: "John"}

    peopleList.push(newPerson);
    console.log(peopleList) // outputs [{id: "123", name: "John"}] 

Check out this Typescript Playground Example

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

Removing an array of file names within a foreach loop with PHP

I'm in the process of implementing a feature that allows users to delete their accounts along with all associated data on the site. Removing the relevant records from the database was straightforward. However, I encountered some challenges when tryin ...

Using i18next to efficiently map an array of objects in TypeScript

I am currently converting a React project to TypeScript and using Packages like Next.js, next-i18next, and styled-components. EDIT: The information provided here may be outdated due to current versions of next-i18next. Please check out: Typescript i18ne ...

What is the reason behind the restriction on using 'this' on the left side of an assignment?

Within the component class, I've been working on this: export class myapp { detail; myarr = ['me', 'myself', 'i']; title = this.myarr[0]; this.detail = this.title ; //error } I'm curious why `this.detail` ...

Error encountered in Java when attempting to use a generic type as a parameter

public class pencil<T> { private T []a; public pencil(T[] a) { this.a=(T[]) a; } public void pencil1() { for (int i = 0;i<a.length;i++) { if (a[i]== "pen") { System.out.println("pen"); ...

Switching between different types of generic functions in typescript

Is there a way to convert between these two types of generic functions: type Foo=<S>(a: S) => S type FooReturnType = ReturnType<Foo> // unknown type Bar<S> = { (a: S): S } type BarReturnType = ReturnType<Bar<string> ...

react-hook-form replaces the onChange function causing delays in updating the value

Recently, I created a unique Select component utilizing useState and onChange. I attempted to integrate this custom component with the powerful react-hook-form. Allow me to share the code snippet for the bespoke Select component. const Select = forwardRef ...

ESlint is unable to parse typescript in .vue files

After using vue ui to build my project, here is the content of my package.json: "@vue/cli-plugin-eslint": "^4.1.0", "@vue/cli-plugin-typescript": "^4.1.0", "@vue/eslint-config-standard": "^4.0.0", "@vue/eslint-config-typescript": "^4.0.0", "eslint": "^5.1 ...

What is the best way to add an array of objects to MongoDB using Golang and the official MongoDB Driver?

I'm currently facing an issue with inserting an array of objects and adding new objects to the existing array. The problem arises when I insert the array, resulting in an object nested inside an array within the parent array. Below is a snippet of my ...

How can I enable SCSS/SASS support on Parcel-Angular5?

I started a project using angular cli. My intention is to incorporate scss into the project. In the terminal of WebStorm, I entered : ng set defaults.styleExt scss I proceeded by renaming all the .css files to .scss and adjusted the imports accordingly ...

Implementing Bootstrap 4 in an Angular 9 project without the use of JQuery

Currently, I am actively working on detaching all JQuery dependencies within my Angular project. Most of the dependencies stem from utilizing Bootstrap 4 components. Eliminating dropdowns and removing all instances of data-*** seemed to help in this proc ...

How to extract PHP array keys and values from PostgreSQL function parameter to update database records

I am attempting to pass an array of key value pairs as a parameter to a postgresql function. The format of the array is as follows - array(10) { ["OWNER"]=> string(3) "ERP" ["SOURCE"]=> string(7) "Unknown" ["PRIORITY"]=> string(6) "Medi ...

Tips for identifying and handling errors in Playwright

I'm going crazy trying to handle a TimeoutError that I know is coming. Currently, I'm testing the Hidden Layers scenario from UI Testing Playground in Playwright Node.js and I want to see if there's a way to prevent the TimeoutError from cau ...

Monitor the input value for any changes in Angular 8 using the listen component

Hey there! I'm currently working with a component that includes the input @Input() userId: number[] = []; to receive a list of user IDs. Specifically, I have integrated this component into another one, such as the news component: <kt-user-post-li ...

Managing the ERR_NAME_NOT_RESOLVED issue

Currently, I am facing a task related to the health check endpoint where I need to receive a response from the backend or encounter a net::ERR_NAME_NOT_RESOLVED error if we are outside of a specific network. When attempting to send a request to my endpoin ...

Can you tell me the meaning of NGX and how it is commonly utilized?

Can you explain NGX to me? I frequently come across it paired with module names in Angular applications. What exactly is NGX and what purpose does it serve? ...

Tips for modifying and refreshing objects in Javascript

Just getting started with JavaScript! How can I update an object with a pre-existing value? const array = []; // Function to assign pre-existing value function Object1(myText) { this.text = myText; } const userText = new Object1("text to edit"); arr ...

In the context of Angular, the ELSE statement continues to run even after the IF condition has been satisfied within

Currently, I am utilizing Angular 11 in conjunction with Firestore. Within my code, I am fetching data using the subscribe method from an API service. Subsequently, I am employing a for loop to extract object values in order to verify if a value within a c ...

Update the data in Firebase, but revert it back to the original state after a few seconds with the use of "angularFire."

I'm currently working on updating data in the Firebase Realtime Database using Angular and AngularFire. The issue I'm facing is that even though the data changes successfully, it reverts back to the original data after a few seconds. Below is the ...

Adjust the width of Google chart to 100% automatically when the page is resized in Angular version 4 or higher

My application has numerous responsive wrappers on the site, each predefined from an API and containing a Google chart. The problem is that when the page initially loads, the charts are rendered at a specific size, and resizing the window only affects the ...

What is the best way to calculate the total of a set of strings that represent

Query: Converting array string elements to integers for summation. Check out my code: str = ["+7", "-3", "+10", "0"] str.map!(&:to_i) sum = 0 str.each do |num| if num.is_a?(Integer) sum += num end end puts sum The issue: Traceback (most r ...