Angular Tour of Heroes, HTTP requests: Argument of type 'Hero' is not assignable to parameter of type 'string'

Issue

In the angular tutorial here, I am copying this tidbit of code:

add(name: string): void {
  name = name.trim();
  if (!name) { return; }
  this.heroService.addHero({ name } as Hero)
    .subscribe(hero => {
      this.heroes.push(hero);
    });
}

The tutorial also explains that: When the given name is non-blank, the handler creates a Hero-like object from the name (it's only missing the id) and passes it to the services addHero() method.

I copied the exact code as far as I am aware, but I am unable to compile due to the error:

Argument of type 'Hero' is not assignable to parameter of type 'string'.

The problem is, I know what it is telling me, but I’m not sure how to get around this. I think I’m trying to cast the string to object of type Hero, but I should not supply an ID here (as the tutorial points out).

Is it safe to not cast it as Hero? How can I proceed in this tutorial?

Thanks in advance.

Solution

This means that your HeroService.addHero method takes a string as a parameter instead of a Hero, but a Hero‘s what you’re passing. Solution is to either just pass name (without the curly braces or as Hero), or rewrite HeroService.addHero to accept a Hero instead of a string.

Answered By – ocket8888

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.