Creating an array object in TypeScript is a straightforward process

Working on an Angular 4 project, I am attempting to declare an attribute in a component class that is an object containing multiple arrays, structured like this:

history: {
  Movies: Array<Media>,
  Images: Array<Media>,
  Music: Array<Media>,
}; 

The Media interface has the following properties:

export interface Media {
  size: number,
  name: String
} 

When trying to push objects into the history elements like this:

this.history.Music.push(music);

Where music has the same type (Media), it throws the error:

1449 ERROR TypeError: Cannot read property 'Music' of undefined

This issue seems to be related to the declaration.

Note: I have tried declaring the arrays as both empty and with initial values, but the error persists.

Answer №1

Set up the history object by initializing it with various properties set to an empty array

history: {Movies: Array<Media>, Images: Array<Media>, Music: Array<Media>} = {
  Movies: [],
  Images: [],
  Music: []
};

Answer №2

If you want to manage historical media items, consider creating a History class:

class History {
    constructor(public Movies: Media[] = [], public Images: Media[] = [], public Music: Media[] = []){}
}

In your component, initialize the history property as follows:

history = new History();

Now you can easily perform actions like adding music to your history:

this.history.Music.push(music);

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

Issue with converting form data to JSON format

Having an issue converting a filled form in HTML to a JSON request for sending to the server via HTTP POST. Despite having a filled form, the JSON request only shows an empty array. Here is the JavaScript snippet: $("#submitSurveyBtn").on("click", functi ...

Strategies for handling user typos in a JavaScript prompt

Hi there! Just wanted to say that I'm new to this website, so please forgive any posting mistakes I might make. I'm currently taking a web technology class where we're learning JavaScript. In a previous lesson, we covered HTML5 and CSS. Our ...

What is the process for retrieving the result of a promise at a later time?

var screencastId = 'abc' var a = youtube.get(screencastId); a.then(function(screencast) { // Great, the screencast information is now available. console.log(screencast); }); // How can I access the `screencast` variable below? connection.be ...

Node.js API requests often result in undefined responses

As a newcomer to Node.JS, I am currently experimenting with calling a REST API using the GET method. I have utilized the 'request' package available at this link. While the call functions correctly, I encounter an issue when attempting to return ...

What steps are required to transition an Angular application developed without the Angular CLI into an Angular CLI project?

I've created an Angular app using tools like NPM (without utilizing the Angular CLI). What would be the most efficient way to transition this project into the CLI project structure? I want to have the ability to utilize commands like ng serve. ...

Creating dummy objects from a specific data type in Typescript for the purpose of testing

I'm exploring ways to streamline the creation of mock data for unit testing within an Angular solution. Currently, I am defining interfaces such as: export interface ReferenceDataItemCommon { codeDescription?: string; code: string; deleted?: boo ...

TypeError: Unable to find TextEncoder in mongoose and jest when using TypeScript

Currently, I am working on a project using Node 14 along with Express v4.16.3 and Typescript (v4.7.4). Recently, I added Mongoose (v6.5.2) to the project, and while the logic code seems fine, most of the tests executed by Jest (v26.4.2) are failing with th ...

The system does not acknowledge "ENVIRONMENT" as a command that can be executed either internally or externally, or as a batch file that can be

While running my Next.js application, I encountered the following error in a script: "scripts": { "dev: "ENVIRONMENT=env/.env.development next dev", "check": "npm run format && npm run eslint", "e ...

Loading JavaScript in the background using Java and HtmlUnit

I am currently facing a challenge while navigating a website using HtmlUnit. This particular website adjusts certain buttons and displays or hides certain elements based on JavaScript events. For instance, there is a text input box along with a button th ...

The NodeJs and Express API, integrated with Ejs files, encounters a crash when attempting to retrieve data from the database on the second attempt

I've been assigned the task of developing an API that retrieves data from a database and presents it on the frontend. This is my first time working with APIs, and I've encountered some challenges along the way. The database I'm using is call ...

Error encountered in SelectInput.js file of React MUI 4: line 340 - TypeError: Unable to access properties of undefined (specifically 'value')

An issue arises when an empty array is provided as the options. The error message: SelectInput.js:340 Uncaught TypeError: Cannot read properties of undefined (reading 'value') at SelectInput.js:340:1 at Array.map (<anonymous>) ...

What could be the reason for the counter not being incremented when the button is clicked

While attempting to increase the counter in my test, I encountered an issue where pressing the button did not change the value. I tried using both fireEvent from React testing library and React test utils, but the value remained at 10. My project is using ...

Function exhibiting varying behavior based on the form from which it is called

Currently, I'm utilizing AJAX to execute a server call, and I've noticed that the behavior of my function varies depending on its origin. Below is an excerpt of the code that's causing confusion: <html> <body> <script> ...

Generic parameter with a union type

The proxy function returns a randomly determined type. const numbersArray = [1,2,3,4]; const stringsArray = ['1','2','3','4']; function func<T>(array: T[]): T[][] { return [[array[0], array[1]], [array[2], ...

Setting up Storybook with Tailwindcss, ReactJS and Typescript: A comprehensive guide

What is the best way to configure Storybook to handle Tailwindcss styles and absolute paths? Just a heads up, this question and answer are self-documenting in line with this. It was quite the process to figure out, but I'm certain it will help others ...

Is it possible to send the value of an array to a client along with a JavaScript file using a read

I have a server set up with node.js that is using node-mysql to extract data and store it in an array called FRUITS. Now, I am looking for a way to pass this array's value (FRUITS) to the client side JavaScript file that I will be sending using &apos ...

The mouseenter event in jQuery is failing to trigger

I'm encountering an issue with the mouseenter event on a div section of my webpage. I am attempting to alter the background color of this div when the mouse enters, but it seems to be disregarded. This is the basic HTML code: <div id="services" c ...

Angular Universal: Execution of ngAfterViewInit occurring on the server side rather than the client side

While working on my server-rendered Angular application with Angular 17, I ran into a curious issue revolving around the ngAfterViewInit lifecycle hook. The situation arises when I call an init function within ngAfterViewInit, which relies on an API reques ...

JavaScript makes Chrome Hard Reload a breeze

We've created a browser-based app using AngularJS and are currently testing it with a group of clients. One major challenge we're facing is explaining how to "Empty Cache and Hard Reload" using the Chrome browser (by pressing F12, then clicking o ...

Automatically choose radio buttons within an li element in a loop

Hey there, I'm new to SO and this is my first question. As a bit of a newbie, I found this jquery code snippet on another SO answer that I want to use. The function I'm aiming for is the same, but the markup structure in my HTML is different bec ...