dom_ahdigital
dom_ahdigital

Reputation: 1679

Add objects to an array in typescript

When a user clicks some items on my web page, I want to store the item details in an array of objects like this:

[{ "color": "blue", "shape": "square" } , { "color": "red", "shape": "triangle" }]

However, the following code throws an error when I try to push(tempObj):

export class MyComponent implements OnInit {
  itemsClicked: {color: string, shape: string}[] = [];

  ngOnInit(): any { }

  onItemClick(color, shape) {
    let tempObj = {};
    tempObj["color"] = color;
    tempObj["shape"] = shape;
    this.itemsClicked.push(tempObj);
  }
}

Error:

Argument of type '{}' is not assignable to parameter of type '{ color: string; shape: string; }'.

Upvotes: 0

Views: 79

Answers (2)

Nino Filiu
Nino Filiu

Reputation: 18551

Also you might encounter an error with tempObj like

Property 'color' does not exist on type '{}'.

Building the whole object directly should fix it

export class MyComponent implements OnInit {
  itemsClicked: {color: string, shape: string}[] = [];
  ngOnInit(): any { }
  onItemClick(color: string, shape: string) {
    this.itemsClicked.push({ color, shape }); // <--
  }
}

Upvotes: 0

Aplet123
Aplet123

Reputation: 35560

[] is not an array of any type, it's an empty array, so you can't push anything to it. Give it an actual type:

itemsClicked: {color: string, shape: string}[]

Also make sure you assign it in the constructor.

Upvotes: 2

Related Questions