Search code examples
javascriptangularmethodsangular-services

What is Pipe number ( | number ) in the deleteHero method of hero.service.ts in Angular v5 Tour of Heroes Tutorial


Javascript / Typscript is new to me. As i work through the Angular Tour of Heros, I keep seeing syntax I have not seen in my C# programming.

In the Tour of Heroes Angular v5 tutorial, there is some javascript syntax I can't understand.

Can someone help me understand what the "| number" is in the deleteHero method definition?

Ref: https://angular.io/tutorial/toh-pt6#add-heroservicedeletehero

    /** DELETE: delete the hero from the server */
deleteHero (hero: Hero | number): Observable<Hero> {
  const id = typeof hero === 'number' ? hero : hero.id;
  const url = `${this.heroesUrl}/${id}`;

  return this.http.delete<Hero>(url, httpOptions).pipe(
    tap(_ => this.log(`deleted hero id=${id}`)),
    catchError(this.handleError<Hero>('deleteHero'))
  );
}

Solution

  • This is a union type. You can read about union types in typescript here.

    Basically hero: Hero | number means that the parameter named hero can be of type Hero OR of type number, and the function will work with either.