What is a Generic Type in an Array?

Currently, I'm working on designing a mockup app that displays data in the form of buttons in a list. I have successfully implemented most of the features but I have encountered a problem. I have initialized an array and another class to manage the data.

-items.ts

  export class ItemPage {

  items: Item[] = [];

  constructor() {

    this.items.push(
      new Item(1, 'Apple', 'Green', 6, true));
    this.items.push(
      new Item(2, 'Banana', 'Yellow', 15, false));
  }

The data class is structured like this

-item.ts

export class Item {
  constructor(
    id: number,
    fruit: string,
    color: string,
    quantity: number,
    onStock: boolean,
  ) { }
}

Currently, I'm facing an issue with items: Item[] = []; when I run ionic serve. The error message states

Generic type 'Item' requires 2 type argument(s)
and
type Item<K extends string, T> = { [P in K]: T; } Construct a type with a set of properties K of type T
.
I have tried to troubleshoot it on my own but haven't been successful. Does anyone have an idea on how to resolve this?

Thank you

Answer №1

I attempted to recreate the issue, but instead, I ended up with two empty objects. It appears that the error is related to not setting the properties in your class as public. To resolve this, simply adjust your class like so:

export class Item {
  constructor(
    public id: number,
    public fruit: string,
    public color: string,
    public quantity: number,
    public onStock: boolean,
  ) { }
}

After making this change, everything seemed to work properly: Plunker

HOWEVER, I would recommend using interfaces instead, especially if you do not require functions within classes or have another specific reason. You can create an interface like so:

export interface Item {
  id: number;
  fruit: string;
  color: string;
  quantity: number;
  onStock: boolean;
}

constructor(private navController: NavController) {
  this.items.push({id:1, fruit:'Apple', color:'Green', quantity:6, onStock:true});
  this.items.push({id:2, fruit: 'Banana',color:'Yellow',quantity:15,onStock:false})
}

I hope this information proves helpful!

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 ForbiddenError has struck again, this time wreaking havoc in the realms of Node.js, Express.js

I am currently adapting this GitHub sample application to utilize Express instead of KOA. However, I am encountering an Access Denied issue when the / route in Express attempts to load the index.html. What specific modifications are required in the code be ...

Identified the category

How can I retrieve the default option from a list of options? type export type Unpacked<T> = T extends Array<infer U> ? U : T; interface getDefaultValue?: <T extends Option[]>(options: T) => Unpacked<T>; Example const options = ...

A guide on logging errors triggered within reducers

I'm facing a challenge in Redux where I am unable to get error messages logged to the console. My stack includes React, Redux Toolkit, and TypeScript. Here is a snippet of one of the reducers I've implemented: // Reducer const removeResourceRedu ...

Transform array sequences into their own unique sequences

Reorder Array of List to Fit My Custom Order Current Output: [ { "key": "DG Power Output", "value": "6.00", "unit": "kWh", }, { "key": "DG Run Time", "value": "5999999952", "unit": "minutes", }, { "key": "Fuel Level (Before)", "value": "8.00" ...

add the string to the chat messages array in the observable

Currently, I am in the process of developing a chat application and my goal is to showcase the user's messages in the chatroom, referred to as the feed in this project. I have already implemented a function called getMessages() that displays all exist ...

I'm unable to import correctly using the --compiler option

Having an issue here. I'm trying to bring in the typescript compiler. I used this command: bit import bit.envs/compilers/typescript --compiler Unfortunately, it didn't work. This is the error message: bit import [ids...] import components in ...

Navigating with Angular 2: Redirecting Azure AD login URI

I am currently exploring Azure AD integration for logging into an Angular 2 application. The Github link provided below demonstrates a simple method to log in without the use of any authentication libraries. Sign in via Microsoft Graph using Typescript an ...

Is it possible for me to change a selector value?

Currently, I am working on an app that utilizes NGRX. I have a question regarding the store being a readonly place where direct object mutation is not allowed. However, I am unsure about the use of selectors. For example, consider the following NGRX sele ...

Are there any more efficient methods to retrieve an object from an arrow function in TypeScript?

Trying to retrieve an object from an arrow function is posing a challenge for me, especially with the following function f: myMethod(f: data => { return { someField: data.something }; }); I am aware that for simple types, you can condense the arrow ...

The output from the second request using RxJS

I am facing an issue with returning an Observable from the second request. Here is the scenario I am encountering: commandRequest(action:string, commandData:any):Observable<CashDesckResponse> { let command:CashDeskRequest; //ask my backend f ...

Determining the location of an input field in Angular

I am currently utilizing Angular for my project. Within the framework, I have a primary component called name.component.ts/html. By utilizing this base component, I have created four additional components - first-name.component.ts/html, last-name, middle-n ...

How can Typescript generics verify the value type for a specific key in a generic object?

I am facing an issue with a function called sortData. This function takes in a key and is designed to sort an array of objects based on the values for that key: function compare(v1: string | number, v2: string | number) { return (v1 < v2 ? -1 : v1 > ...

Tips for setting up nested folders using Node.js on a Windows machine:

Is there a way to use Nodejs in Windows 10/11 to create a parent folder and then add a new folder inside of that parent folder, like this: parent/child within the Documents folder? ...

Dealing with Undefined TypeScript Variables within an array.forEach() loop

Could someone help me understand my issue? I have an array of a specific object, and I am trying to create a new array with just the values from a particular field in each object. I attempted to use the forEach() method on the array, but I keep encounteri ...

What is the best way to represent a directory structure in JSON using a C# data type?

My directory structure is as follows: v1 file1.txt file2.txt common common.txt I need to create a C# function that can traverse this directory structure and generate JSON output. The expected JSON format is like this: { "v1&qu ...

Issue with subscribing in a MEAN stack application

Currently, I have completed the backend development of my application and am now working on the frontend. My focus at the moment is on implementing the register component within my application. Below is the code snippet for my Register Component where I a ...

Master the Art of Scrolling Lists in Ionic 2

I am currently using Ionic2 for my project. One of the challenges I'm facing is scrolling to the top of a list when a specific event, called messageSend, occurs. Let me show you the code for this: <ion-content padding class="messages-page-conten ...

Using TypeScript for abstract methods and polymorphism

What do I need to fix in order for this code to function properly? abstract class Animal { // No constructor ... public abstract me():Animal; } class Cat extends Animal { constructor() { super(); } // Why does this no ...

Using TypeOrm QueryBuilder to establish multiple relations with a single table

Thank you for taking the time to read and offer your assistance! I am facing a specific issue with my "Offer" entity where it has multiple relations to "User". The code snippet below illustrates these relationships: @ManyToOne(() => User, (user) => ...

Changing a string into a date format with the help of JavaScript AngularJS

My string is as follows: 13-12-2017 05:05 AM I am looking to convert it to the following format: Date 2017-12-13T05:05:00.000Z Attempted Solution: var mydate = '13-12-2017 05:05 AM'; var selectedDate = new Date(mydate); Upon logging the selec ...