0

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; }'.

3
  • You need to declare the type of tempObj to be the same as {color: string, shape: string}. Commented Jan 15, 2021 at 15:55
  • You have edited the question and now the answer given doesn't fit this. Please don't do that - if you have a new question ask it separately. Commented Jan 15, 2021 at 16:03
  • Probably just a question typeo, and probably not causing the error, but colour and color and not the same spelling for variable names. Commented Jan 15, 2021 at 16:42

2 Answers 2

2

[] 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.

Sign up to request clarification or add additional context in comments.

4 Comments

How to assign in constructor?
Either add a constructor like constructor() { this.itemsClicked = []; } or let typescript desugar it for you with itemsClicked: {color: string, shape: string}[] = [].
I updated OP with the suggested code, but still getting type error.
tempObj isn't being typed correctly due to first being initialized as {}. See Lazy Object Literal Initialization for fixes.
0

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 }); // <--
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.