[英]TS2322: Type 'Promise<Hero | undefined>' is not assignable to type 'Promise<Hero>'
I'm learning angular4 from angular tutorial . 我正在从角度教程中学习angular4。 Below is a function to get a hero from service's function:
以下是从服务功能中获得英雄的功能:
@Injectable()
export class HeroService {
getHeroes(): Promise<Hero[]> {
return new Promise(resolve => {
// Simulate server latency with 2 second delay
setTimeout(() => resolve(HEROES), 2000);
});
}
getHero(id: number): Promise<Hero> {
if (id < 0) {
throw new Error('Hero is not found.');
}
return this.getHeroes()
.then(heroes => heroes.find(hero => hero.id === id));
}
}
On execution it throws error: 执行时会引发错误:
TS2322: Type 'Promise<Hero | undefined>' is not assignable to type 'Promise<Hero>'.
Type 'Hero | undefined' is not assignable to type 'Hero'.
Type 'undefined' is not assignable to type 'Hero'.
Anybody else also faced this issue ? 还有其他人遇到这个问题吗? Please help.
请帮忙。 Thank you.
谢谢。
@Component({
selector: 'hero-detail',
templateUrl: './hero-detail.component.html'
})
export class HeroDetailComponent implements OnInit {
@Input() hero: Hero;
constructor(private heroService: HeroService, private route: ActivatedRoute, private location: Location) { }
ngOnInit(): void {
this.route.paramMap
.switchMap((params: ParamMap) => this.heroService.getHero(+(params.get('id') || -1)))
.subscribe(hero => this.hero = hero);
}
goBack(): void {
this.location.back();
}
}
The reason typescript throws this error is because Array.find
will return undefined
when all elements don't matched the condition hero.id === id
. 类型
Array.find
引发此错误的原因是,当所有元素都不符合条件 hero.id === id
时, Array.find
将返回undefined
。
Refer doc about Array.find
: 请参考有关
Array.find
文档 :
The find() method returns the value of the first element in the array that satisfies the provided testing function.
find()方法返回满足提供的测试功能的数组中第一个元素的值。 Otherwise undefined is returned.
否则返回undefined。
To avoid the error, you should change your function's return type to Promise<Hero | undefined>
为避免该错误,应将函数的返回类型更改为
Promise<Hero | undefined>
Promise<Hero | undefined>
. Promise<Hero | undefined>
。
getHero(id: number): Promise<Hero | undefined> { // <----mention here for return type
return this.getHeroes()
.then(heroes => heroes.find(hero => hero.id === id));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.