Created an Angular11 project with strict set to true in CompilerOptions as I thought it's a good idea to detect potential errors at compile time.
strict
true
CompilerOptions
Then try to follow the Angular official website tutorial which doesn't turn on strict mode. In the example, it uses Observable when a service returns some hard-coded mock data. Now this doesn't compile due to hero potentially is undefined. And the compiler complains that type Hero | undefined cannot be assigned to type Hero. Note that HEROES is hard-coded mock data but in production it's retrieved from a database. Turning off strict mode gets rid of the complier errors but what if I want to turn on strict mode and the data is not mocked. How to deal this?
Observable
hero
undefined
type Hero | undefined cannot be assigned to type Hero
HEROES
getHero(id:number): Observable<Hero> { return of(HEROES.find((hero => hero.id === id))); }
You could search for result where the var hero is a valid Hero:
Hero
getHero(id:number): Observable<Hero> { return of(HEROES.find((hero => hero && hero.id === id))); }
1.4m articles
1.4m replys
5 comments
56.9k users