Angular/Typescript:声明传递给 "find" 的 lambda 类型 return

Angular/Typescript: declare return type of lambda passed to "find"

所以,我正在参加培训课程并拥有 Angular 服务:

import {Exercise} from "./exercise.model";

export class TrainingService{
  private availableExercises: Exercise[] = [
    { id: 'crunches', name: 'Crunches', duration: 30, calories: 8 },
    { id: 'touch-toes', name: 'Touch Toes', duration: 180, calories: 15 },
    { id: 'side-lunges', name: 'Side Lunges', duration: 120, calories: 18 },
    { id: 'burpees', name: 'Burpees', duration: 60, calories: 8 }
  ];

  private currentExercise: Exercise | null = null;

  getAvailableExercises() : Exercise[] {
    return this.availableExercises.slice();   //// slice() returns a copy (new object), not a reference
  }

  startExercise(exerciseId: string) : void {
    this.currentExercise = this.availableExercises.find( (exercise: Exercise) : Exercise | null => 
        {exercise.id === exerciseId});
  }

}

我刚刚添加了 startExercise)(),但出现错误。当然,我可以重新编码它而不使用 find(),但我更愿意知道这里发生了什么。来自强类型语言背景,我强制执行类型检查。

具体错误是

  Type 'undefined' is not assignable to type 'Exercise | null'.

18     this.currentExercise = this.availableExercises.find( (exercise: Exercise) : Exercise | null => {exercise.id === exerciseId});
       ~~~~~~~~~~~~~~~~~~~~


Error: src/app/training/training.service.ts:18:81 - error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value.

18     this.currentExercise = this.availableExercises.find( (exercise: Exercise) : Exercise | null => {exercise.id === exerciseId});

如何修复该代码?

typescript 编译器知道数组 AvailableExercises 是 Exercise[] 类型,所以你实际上不必定义 (exercise: Exercise) : Exercise |再次为 null 作为类型 Exercise.

刚放:

this.currentExercise = this.availableExercises.find(exercise => exercise.id === exerciseId); 

应该已经开始工作了。您可以检查它是否找到任何东西,因为 array.find 将 return 谓词为真且未定义的第一个元素。所以

if (!this.currentExercise) {
   // Here some error or your own idea
}

在这里,很抱歉编辑了答案,但我真的不能在commants中编码格式。

  1. private currentExercise: Exercise | undefined;

  2. this.currentExercise = this.availableExercises.find( (exercise: Exercise) => {exercise.id === exerciseId}); 有效