gpt4 book ai didi

javascript - TS2322 : Type 'Promise' is not assignable to type 'Promise'

转载 作者:搜寻专家 更新时间:2023-10-30 21:29:11 26 4
gpt4 key购买 nike

我正在从 angular tutorial 学习 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();
}
}

最佳答案

typescript 抛出这个错误的原因是因为 Array.find返回undefined 所有元素都不符合条件 hero.id === id .

引用 doc 关于Array.find :

The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.


为避免错误,您应该将函数的返回类型更改为 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));
}

关于javascript - TS2322 : Type 'Promise<Hero | undefined>' is not assignable to type 'Promise<Hero>' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45854373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com