What is the method for creating a new array of objects in Typescript with no initial elements?

After retrieving a collection of data documents, I am iterating through them to form an object named 'Item'; each Item comprises keys for 'amount' and 'id'.

My goal is to add each created Item object to an array called 'Items'. However, when I initialize this array at the beginning (currently declared as var itemObjects: [Item]) and proceed to push each item like so:

snapshot.forEach((doc: any) => {
let docData = doc.data()
let items = docData.items
items.forEach((item: any) => {
  let itemObject = new Item(item.amount, item.transactionType)
  console.log("converted item to Item Object:", itemObject)
  itemObjects.push(itemObject)
})

An error occurs: Unhandled error TypeError: Cannot read properties of undefined (reading 'push')\n

I suspect that my initialization of the variable array is incorrect. Any assistance would be greatly appreciated. Thank you.

EDIT- Here's the additional code snippet (pertaining to the Item class):

interface IItem {
amount: number
id: string
}

export class Item implements IItem {
 amount: number
 id: string

 constructor(amount: number, id: string) {
  this.amount = amount
  this.id = id
  }
 }

Answer №1

The variable is being declared but not initialized. Once TypeScript removes the type annotations, the resulting JavaScript code is simply:

var itemObjects

To resolve this, assign a value to the variable like so:

var itemObjects: Item[] = []
                        ^^^^

Another issue that has been addressed (as shown above) is the use of [Item] as a tuple with a single Item. At runtime, it behaves like an array, but can only have exactly one Item. It is recommended to use Item[] to indicate an array of items instead.

Answer №2

If you want to create a typed array, you have a couple of options:

let items = new Array<Item>();

or

let items: Item[] = [];

Both methods will produce the same result.

By the way, why not consider using the map function instead of forEach?

let items = docs.map((item: any) => new Item(item.amount, item.id));

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

Implement a transformation on the API endpoint's JSON data to prepare it for display in a React

I'm currently developing a React application and have created a component to display tabular data. The API endpoint I am calling returns data in the following format: { "bitcoin": { "usd": 48904, "usd_market_cap": 9252 ...

Is it possible to protect assets aside from JavaScript in Nodewebkit?

After coming across a post about securing the source code in a node-webkit desktop application on Stack Overflow, I began contemplating ways to safeguard my font files. Would using a snapshot approach, similar to the one mentioned in the post, be a viable ...

Can someone please explain how I can extract and display information from a database in separate text boxes using Angular?

Working with two textboxes named AuthorizeRep1Fname and AuthorizeRep1Lname, I am combining them in typescript before storing them as AuthorizeRep1Name in the database. Refer to the image below for the result. This process is used to register and merge the ...

"Exploring Angular 9: A guide to retrieving form data with an array of objects [Revised as of July 29th, 2020

I am encountering an issue with my Angular 9 form code. I am getting the error "ERROR TypeError: Cannot read property 'mobile_number' of undefined" and I need help in resolving this problem. <form (ngSubmit)="processForm()"> & ...

CoffeeScript equivalent of when the document is loaded

Recently, I've been delving into Coffeescript for my web application, but I'm encountering a frustrating issue. The methods are not being called until I manually reload the page. I suspect that the missing piece may be the $(document).ready(func ...

Creating a text box that displays an inverted input

Hello, I'm looking to create a text box where if I input 1 then 2, it will display 21. Then if I enter 3, it should show 321. I am currently using Vue.js on my front end. Here is what I have attempted so far: I experimented with methods such as watc ...

Solving compatibility problems with jquery AJAX requests on multiple browsers

searchCompanyExecutives: function(criteria, callback) { var params = $j.extend({ type: "GET", data: criteria, url: "/wa/rs/company_executives?random=" + Math.floor(Math.random() * (new Date()).getTime() + 1), ...

Create an object that may have any number of keys, but must have at least one key defined

Is there a way to accomplish this task? type Plant = "rose" | 'tulip' | 'daisy' type PlantCollection = { [p in Plant]?: number } const validPlantCollection: PlantCollection = { rose: 1, daisy: 2 } const emptyCollectionShouldBeRejec ...

Showing identification and name within a URL path - Angular

I am looking to update a URL path within a website from http://localhost:4200/viewbrand/1 to http://localhost:4200/viewbrand/1/soap, where "soap" is added after the ID in the path. The current code in the routing module.ts file is as follows: { path: &apo ...

The process of batch file conversion and how to effectively utilize it

I am facing an issue with a small batch script that I have been working on. The purpose of this batch script is to execute a Javascript file that converts an XML file to a csv file, followed by running a Python script to analyze the created csv file and ge ...

Adjusting the letter spacing of individual characters using HTML and CSS

Is there a way to set letter-spacing for each character with different sizes as the user types in a text box? I attempted to use letter-spacing in CSS, but it changed all characters to the same size. Is there a possible solution for this? Here is the code ...

Creating a Yup field that is an object and making it required when another field is set to true in the validation process

Just getting started with Yup validation and I'm facing an issue. I am attempting to make certain fields required based on a condition. Specifically, I want the digital object to be required only if hasDigital is true; otherwise, it should be optional ...

Utilizing jQuery with live content to determine dimensions as required

Within my web application, I have a page that dynamically retrieves a view with both HTML and JavaScript. The JavaScript is responsible for rendering a chart into the retrieved view. The problem arises because the chart library I am utilizing (flot) necess ...

Utilizing Firebase 9.0.1 Functions in Vue.js 3

As a newcomer to Vue, I decided to tackle my second tutorial which involved integrating Firebase backend with Vue. However, the tutorial was based on Vue 2 and an older version of Firebase. Determined to stay current, I set out to replicate the project usi ...

Vue-resource is returning a Promise object

How do I access the response data in an Ajax call? When I log response.text(), it displays a PromiseObj. Console PromiseObj context: undefined promise: Promise {status: "resolved", result: ")]}',↵{\"Result\":\"SUCCESS\",&bs ...

FusionMaps XT integration with VueJs: Troubleshooting connectorClick events issue

I am experiencing some issues with events connectorClick on my VueJS processed map. When I click on the connector line in the example below, the alert function does not seem to work as expected. Vue.use(VueFusionCharts, FusionCharts); let grphMap = new ...

What could be the reason for this simple sails socket not functioning properly?

Just curious why the simple web socket code below isn't functioning? io.socket.on('user', function(event){ console.log("RECEIVED EVENT:",event); }) I have included sails.io.js in my index file and the above code is located in a test.js ...

What is the process for importing npm scoped packages with @ symbol in Deno?

Having some trouble with importing @whiskeysockets/baileys in Deno. Here's the code snippet I'm using: import * as a from "npm:@whiskeysockets/baileys"; console.log(a); When I try to run deno run main.ts, it throws the following error: ...

Tips for efficiently handling state across various forms in separate components using only one save button within a React-Redux application

I am currently developing an application that combines a .NET Core backend with a React frontend, using React Hook Form for managing forms. Unlike typical single-page applications, my frontend is not built in such a way. On a specific page of the applicat ...

Save the user input to a dedicated text file

I am working with a couple of select tags that generate an array. Previously, I was only logging the array to the console upon pressing the SUBMIT button, but now I want to save it to a separate text file. Here is my main.html code: <form method="POS ...