我正在向angular4学习角教程。下面是从服务的功能中获取英雄的函数:
@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));
}
}在执行时,它会引发错误:
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'.还有其他人也面临这个问题吗?请帮帮忙。谢谢。
@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();
}
}发布于 2017-08-24 06:42:19
类型记录抛出此错误的原因是,当undefined所有元素与条件 hero.id === id不匹配时,Array.find将返回。
参考文档关于Array.find
find()方法返回数组中满足所提供的测试函数的第一个元素的值。否则将返回未定义的.。
为了避免错误,您应该将函数的返回类型更改为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));
}https://stackoverflow.com/questions/45854373
复制相似问题