Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

Typescript strict mode filter Observable

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.

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?

getHero(id:number): Observable<Hero> {
    return of(HEROES.find((hero => hero.id === id)));
  }
question from:https://stackoverflow.com/questions/65878443/typescript-strict-mode-filter-observable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could search for result where the var hero is a valid Hero:

getHero(id:number): Observable<Hero> {
    return of(HEROES.find((hero => hero && hero.id === id)));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...