首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TS2322:键入'Promise<Hero \ undefined>‘不能指定键入'Promise<Hero>’

TS2322:键入'Promise<Hero \ undefined>‘不能指定键入'Promise<Hero>’
EN

Stack Overflow用户
提问于 2017-08-24 06:25:11
回答 1查看 4.5K关注 0票数 2

我正在向angular4学习角教程。下面是从服务的功能中获取英雄的函数:

代码语言:javascript
复制
@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));
    }
}

在执行时,它会引发错误:

代码语言:javascript
复制
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'.

还有其他人也面临这个问题吗?请帮帮忙。谢谢。

代码语言:javascript
复制
@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();
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-24 06:42:19

类型记录抛出此错误的原因是,当undefined所有元素与条件 hero.id === id不匹配时,Array.find将返回

参考文档关于Array.find

find()方法返回数组中满足所提供的测试函数的第一个元素的值。否则将返回未定义的.。

为了避免错误,您应该将函数的返回类型更改为Promise<Hero | undefined>

代码语言:javascript
复制
getHero(id: number): Promise<Hero | undefined> {    // <----mention here for return type
  return this.getHeroes()
             .then(heroes => heroes.find(hero => hero.id === id));
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45854373

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档