Miguel Moura
Miguel Moura

Reputation: 39484

Cast array to Array of Type Message

I am receiving the following from an API response in Angular

(response) => {

  let messages: Message[] = response.messages;

  for (let message: Message in messages) {

    let description = message.description;

  }

But in let description = message.description; I get the error:

Property 'description' does not exist on type 'string'.

Is this because I am using a class instead of an interface?

Should message be considered of type Message in my code?

The response is something like:

[
  { description: "Some description", type: "1029BA" },
  { description: "Other description", type: "20sdBC" }
]

And Message is a class.

export class Message {

  description: string;
  type: string;

  constructor(description: string, type?: string) {
    this.description = description;
    this.type = type;
  }    

}

Upvotes: 2

Views: 161

Answers (1)

Jimmy Hedström
Jimmy Hedström

Reputation: 571

Change your for-in loop to a for-of loop, as yo are looping over the keys and not the values in the array:

for (let message of messages) {

  let description = message.description;

}

Upvotes: 5

Related Questions