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

When a user right-clicks on certain words, the menu opens using JavaScript

Looking to implement a custom context menu that opens when specific words are right-clicked by the user in JavaScript. I have been searching for a solution for quite some time now. The word should be recognized based on an array of specific words. Can some ...

CreateAsyncModule using an import statement from a variable

When trying to load a component using defineAsyncComponent, the component name that should be rendered is retrieved from the backend. I have created a function specifically for loading the component. const defineAsyncComponentByName = (componentName: strin ...

Exploring AngularJS with Filtering for Advanced Search Results

Currently, I have a search box that successfully searches values in a table using my code. <tr ng-repeat="b in bugs | filter:searchText"> Now, I want to take it one step further by allowing users to search specific columns if they include a colon i ...

AngularJS ng-repeat - cascading dropdown not refreshing

I'm dealing with an AngularJS issue where I'm trying to create a cascade dropdown like the one below: <div class="col-sm-2 pr10"> <select class="PropertyType" ng-controller="LOV" ng-init="InitLov(140)" ng-model=" ...

Saving JSON format in VueX State Management

I'm relatively new to using Vue/VueX and I am exploring methods for storing JSON data in the VueX state. Initially, it seemed like a simple task: state { jsonthing: { ... } } However, I encountered an issue where getters return an Observer type ins ...

What is the best way to update the state while invoking a component?

Just starting out with react and already hitting a roadblock. I've created an Article Topper component that features a logo, title, and share buttons, which is repeated throughout the site above each article. The issue I'm facing is updating the ...

Using the "i" parameter in a Lodash for loop results in undefined, however, it functions properly with specific values set

My goal is to use Lodash to search for specific integer values in an object and then store some of those values in an array. The integers are variable and come from a separate array, but I am consistently getting undefined as the result. If I manually inp ...

Having trouble retrieving data using a custom URL in Axios with ReactJs

My knowledge of Reactjs is still new and I am currently working on a project using nextjs. I have a component called Trending.js that successfully fetches data from the URL "https://jsonplaceholder.typicode.com/users". However, when I try to change the U ...

I'm just starting out with Python and I'm wondering how I can access the initial values for precipitation, temperature, wind gust, and humidity

from selenium import webdriver import time PATH = "C:\Program Files (x86)\chromedriver.exe" driver = webdriver.Chrome(PATH) driver.get("https://www.metoffice.gov.uk/weather/forecast/gcvwr3zrw#?date=2020-07-12") time.sleep(5 ...

Safari 15.6.1 does not support background video playback in Next.js

Currently using Safari version 15.6.1 for a small website project, I have encountered an issue where the video appears frozen with an arrow in the middle. Oddly enough, this problem only occurs on Safari as both Chrome and Firefox display the code correctl ...

Getting the value of data in a string in C#

Looking for advice on extracting the Name Surname from a given object: Object { "HasError":false, "AlertType":"success", "AlertMessage":"Operation has completed successfully", "ModelEr ...

Issue encountered while generating a fresh migration in TypeORM with NestJs utilizing Typescript

I am currently working on a Node application using TypeScript and I am attempting to create a new migration following the instructions provided by TypeORM. Initially, I installed the CLI, configured my connection options as outlined here. However, when I ...

Extract the Top X elements from a multidimensional array

Consider an Array that consists of nested arrays: [ ["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a9a8abe091b6bcb0b8bdffb2bebc">[email protected]</a>", 1, 9, 338], ["2000-01-01", "<a href="/ ...

Exploring the versatility of orderBy and filter in handling cross-referenced content across multiple JSON objects

Is there a way to filter and search for the item name when the item details are sourced from another JSON object? Demo: http://codepen.io/anon/pen/GjAxKX While the rest of the filtering and ordering functionalities are functioning correctly, I am struggl ...

Issues with reading d3.js visualization data from a JSON file

I am currently working on a data visualization project using D3.js and I started with a basic framework that I found on this link The data for my visualization is coming from a json file containing only two values, a string value and an integer. However, ...

Is there a method to enclose a Grafana row with a border?

I recently created a Grafana dashboard using JavaScript and I realized that adding a border around each row would enhance readability. Here is how the current view looks like: https://i.stack.imgur.com/itKYR.png However, it can be difficult to differenti ...

CoursesComponent does not contain a Directive annotation

I have been following a tutorial online at this link: https://www.youtube.com/watch?v=_-CD_5YhJTA Unfortunately, I keep encountering the following error message: EXCEPTION: No Directive annotation found on CoursesComponent Here is an excerpt from my a ...

How to solve the issue of synchronizing data fetching from a json-server and displaying it in the UI with React?

While working with json-server to retrieve data and display it in the UI, I often face a recurring issue that leaves me puzzled. The process of fetching data is asynchronous, which means that setting the state after fetching the data takes some time. As a ...

What is the process for running child_process when a user clicks on a view in an application

Just starting out with Node.js and utilizing express along with hogan or moustache templating for my views. I've successfully used the following code in my routing files, index.js as shown below: /* Test Shell Execute. */ router.get('/shell&apo ...

Stop automatic selection of the last value in ng-options using AngularJS

I'm facing an issue related to AngularJS. The problem I'm encountering is that... In my code, there are two select elements. Whenever I choose an option from the first select, an Ajax call is made using ng-change to populate the second select ba ...