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