javascript - TS2322: Type 'Promise<Hero | undefined>' is not assignable to type 'Promise&a

I'm learning angular4 from angular tutorial.Below is a function to get a hero from service's

I'm learning angular4 from angular tutorial. 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-detailponent.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();
    }
}

I'm learning angular4 from angular tutorial. 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.ponent.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();
    }
}
Share Improve this question edited Aug 24, 2017 at 7:11 Shelly Chen asked Aug 24, 2017 at 6:25 Shelly ChenShelly Chen 852 silver badges11 bronze badges 10
  • can you post this.getHeroes() method and Hero interface . – Rajez Commented Aug 24, 2017 at 6:30
  • There should be Hero class in your code. and you should import it where you use. Wherever this function is put import { Hero } from 'Hero.ts' (be careful about path) and then try again. – Ömer Faruk Kırlı Commented Aug 24, 2017 at 6:33
  • It throws error because heroes.find could return undefined. – Shelly Chen Commented Aug 24, 2017 at 6:47
  • @Shelly can you post your ponent code or where ever you called the getHero method. So it can help us to reproduce your error. – Rajez Commented Aug 24, 2017 at 7:09
  • @Rajez thank you. I added. – Shelly Chen Commented Aug 24, 2017 at 7:12
 |  Show 5 more ments

1 Answer 1

Reset to default 7

The reason typescript throws this error is because Array.find will return undefined when all elements don't matched the condition hero.id === id.

Refer doc about 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.


To avoid the error, you should change your function's return type to 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));
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742373025a4431635.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信