简体   繁体   中英

Angular error TS2322:'Promise<Dish | undefined>' is not assignable to type 'Promise<Dish>'

I learn Angular 5 at Coursera and have problem with Promise theme. I just repeat a code of lector and have an error TS2322. Here is my service file.

import { Injectable } from '@angular/core';
import { Dish } from '../Shared/dish';
import { DISHES } from '../Shared/dishes';
import { of } from 'rxjs';
import { delay } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class DishService {

  constructor() { }

  getDishes(): Promise<Dish[]> {
    return of(DISHES).pipe(delay(2000)).toPromise();
  }

  getDish(id: number): Promise<Dish> {
    return of(DISHES.filter((dish) => (dish.id === id))[0]).pipe(delay(2000)).toPromise();
  }

  getFeaturedDish(): Promise<Dish> {
    return of(DISHES.filter((dish) => dish.featured)[0]).pipe(delay(2000)).toPromise();
  }
}

And The Component Using The Service Is:

import { Component, OnInit } from '@angular/core';
import { Dish } from '../Shared/dish';
import { DishService } from '../services/dish.service';


@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit {

  dishes!: Dish[];

  selectedDish!: Dish;


  constructor(private dishService: DishService) { }

  ngOnInit(): void {
 this.dishService.getDishes()
      .then(dishes => this.dishes = dishes);
  }
  onSelect(dish: Dish){
    this.selectedDish = dish;
  }
}

Then I get error: Type 'Promise<Dish | undefined>' is not assignable to type 'Promise'. Type 'Dish | undefined' is not assignable to type 'Dish'. Type 'undefined' is not assignable to type 'Dish'.ts(2322)

I've think something is wrong with the service.ts file please explain to me.

Your getDish and getFeaturedDish methods claim to be returning a Promise<Dish> but that isn't really a good assumption. If you look at your implementation, you are filtering on the array of dishes, which could result in a dish that doesn't match your filter. Thus, the return type of these methods should indeed be Promise<Dish | undefined> Promise<Dish | undefined> and not Promise<Dish> . TypeScript doesn't know that your DISHES array will be guaranteed to include a dish that matches your filter logic. I think the solution here is to change your method declarations to be be properly typed and handle potential undefined values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM