What is the proper way to initialize the Array<T> in Angular using TypeScript?

I recently developed an Angular 8 application.

Here is a snippet of one of the models I created in TypeScript:

export class Movie
{
  title:string;
  tickets: Array<Ticket>;
}

export class Ticket
{
   name:string;
   price:number;
}

In a specific component (movie), I encountered an issue where the tickets array was not getting initialized when accessing the movie object.

Within the movie.component.ts file:

export class MovieComponent
{
  movieObj:Movie;

  constructor()
  {
    this.movieObj = new Movie();
    console.log(this.movieObj); // outputs title value but not tickets
   //console.log(this.movieObj.tickets[0].name); //undefined 
  }
}

Upon investigating, I discovered that in TypeScript, an Array type is considered an interface (which cannot be directly instantiated).

Could someone please advise on how to properly initialize an Array in TypeScript/Angular?

Thank you!

Answer №1

In the class itself, you have the option to perform the initialization process.

export class Film
{
  genre: string = 'Action';
  actors: Array<Actor> = [{name: 'Actor', role: 'Protagonist'}];
}

Stackblitz Showcase

Answer №2

If you need to define classes for movies and tickets in your application, you can use the following code snippet as a reference.

export class Movie
{
  title:string = 'Movie';
  tickets: Ticket[] = [];
}
export class Ticket
{
   name:string;
   price:number;
}

Answer №3

When creating tickets, it's important to include logic within the constructor of the Movie class.

To set up the property with an empty array of tickets, you can use:

export class Movie
{
  title:string;
  tickets: Ticket[] = [];
}

Whether you use Ticket[] (shorthand syntax) or Array<Ticket> (generic syntax), there is no semantic difference as they are essentially interchangeable.

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

The link function fails to execute

I have created a custom Directive. The issue I am facing is that the html template is not being rendered. Upon debugging, I noticed that the link function is never called because the instance function is also never called. To troubleshoot, I added "debu ...

How can values be extracted from a multi-dimensional array using JSON.parse()?

Here is a JSON array before using JSON.parse: var temp = { "queries": [ { "sample_size": 3, "results": [ { "name": "temperature", "tags": { "Tag": [ "temperature" ] ...

Center align the mat-expansion-panel material component in a vertical orientation

When working with the mat-expansion-panel component alongside a mat-accordion, I've encountered an issue where the items are not aligning vertically at the center/middle. I'm unsure of the proper method to achieve vertical alignment for the conte ...

Enrich TypeScript objects by incorporating additional properties beyond the ones already present

If I have an expression and want to add extra properties without repeating existing ones, how can I achieve that? For instance, if the expression is a variable, it's simple to include additional fields (like adding field e): const x = { a: 1 }; cons ...

The filter() and some() functions are not producing the anticipated output

Currently, I am in the process of developing a filtering mechanism to sift through a dataset obtained from an API. The array that requires filtering contains objects with various parameters, but my aim is to filter based only on specific parameters. For ...

What methods are typically used for testing functions that return HTTP observables?

My TypeScript project needs to be deployed as a JS NPM package, and it includes http requests using rxjs ajax functions. I now want to write tests for these methods. One of the methods in question looks like this (simplified!): getAllUsers(): Observable& ...

Currently, I am utilizing version 6.10.0 of @mui/x-date-pickers. I am interested in learning how to customize the color and format of a specific component within the library

I'm currently using @mui/x-date-pickers version 6.10.0 and I need to customize the color and format for a specific section in the mobile view. How can I achieve this? I want to display the date as "May 31st" like shown in the image below. Is there a ...

Contrast the equality of two arrays with objects

I have two different types of data structures var dataA = [ { "Employee Name": "Mr. X", id: "1" }, { "Employee Name": "Mr. Y", id: "2" }, { "Employee Name": "Mr. Z", id: "3" } ]; var dataB = [ { id: "1", " ...

TypeScript: Error - .map() is an Invalid Function

I have come across numerous questions similar to mine, but the vast majority of them pertain to an Observable, which is not the issue I am facing. The code snippet in question looks like this: selectedItems: Item[] = null; selectedDate: Date = null; subm ...

Struggling to accurately import JSON with TypeScript typings

I am facing a challenge with the file test.json that I want to import in a typed form. { "items": [ { "kind": "youtube#video", "thumbnails": { "default": { "url" ...

Working with nested JSON structures in React without using an array

Attempting to iterate through some JSON data that has the following structure... "array": [ { "controlPanel": "00000000-0000-0000-0000-000000000000", "lastArmed": "2016-10-31T19:36:19.3943138", "lastDisarmed": " ...

Comprehending the inner workings of the reduce() method

After spending hours reading and watching videos to understand the reduce function, I finally had a breakthrough. It wasn't until I took a break, made some food, and came back to my computer that it all clicked. Now, I confidently grasp how the reduce ...

Angular leverages property binding to connect properties and attributes in the component template

Is there a way to use a property, such as a string, to access an attribute of an object? I was thinking of something like this: cIC -> Object with attribute nameDe language -> String with nameDe <p *ngFor="let cIC of this.customerInformati ...

Exploring the ways to access and restructure a Jagged Array using C#

I am working with a 2D array in C# and need to extract one column as a normal array. The array looks like this: int[][] my2DArray = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; How can I achieve this? I want to have the extracted column stored in a new in ...

What is the best method for sending multiple parameters in a POST request using Angular 5?

In my current project, I am using Angular 5 for the front end and Spring Boot for the back end. I need to send a POST request to the REST API with two parameters: idPerson and idProject. The goal is to link the selected Person with the specified Project. H ...

Establish the base value within the dropdown search bar

When working with Angular 2, I encountered an issue while trying to integrate select2 and semantic-ui dropdown for a dropdown search functionality. Everything works fine until I try to set a default value for the data in the edit page. The default value do ...

A guide on implementing nested child routes in AngularJS 2

I have successfully completed routing for two children, but now I want to display nested routes for those children. For example: home child1 child2 | grand child | grand child(1) ...

Utilizing Nested Queries with Arrays in MongoDB Database

Looking to update the nested array elements in the User collection. Here is the initial data: { _id:"000-0000-0001", Roles :{ 0000-0000-0011: //EngagementId ["0000-0000-0111", "0000-0000-0112", "0000-0000 ...

What causes TypeScript to convert a string literal union type to a string when it is assigned in an object literal?

I am a big fan of string literal union types in TypeScript. Recently, I encountered a situation where I expected the union type to be preserved. Let me illustrate with a simple example: let foo = false; const bar = foo ? 'foo' : 'bar' ...

Fake AxiosInstance. In need of obtaining response in a single test

In my api.ts file import axios from 'axios' export const api = axios.create({ baseURL: 'http://localhost:3333/', }) Within my react-page.spec.tsx file: import React from 'react' import '@testing-library/jest-dom&apo ...