错误:没有与此调用匹配的重载。重载 1 of 2

时间:2021-07-23 07:49:03

标签: angular typescript

我在 angular 12.1.1 中收到以下打字稿(ts2769)错误

错误:

No overload matches this call.
  Overload 1 of 2, '(start: number, deleteCount?: number | undefined): Todo[] | undefined', gave the following error.
    Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
      Type 'undefined' is not assignable to type 'number'.
  Overload 2 of 2, '(start: number, deleteCount: number, ...items: Todo[]): Todo[] | undefined', gave the following error.
    Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
      Type 'undefined' is not assignable to type 'number'.

对于以下代码:

import { Injectable } from '@angular/core';

import { of } from 'rxjs';

import {Todo} from "./../model/Todo"

@Injectable({
  providedIn: 'root'
})
export class TodoService {
  todos: Todo[] | undefined;

  constructor() {
    this.todos = [
      {
        id: '111',
        title: "Learn C++",
        isCompleted: true,
        date: new Date(),
      },{
        id: '222',
        title: "Learn React",
        isCompleted: true,
        date: new Date(),
      },
      {
        id: '333',
        title: "Learn Angular",
        isCompleted: false,
        date: new Date(),
      },
    ];
   }


   getTodos(){
     return of(this.todos)
   }
  
   addTodo(todo: Todo) {
     this.todos?.push(todo)
   }

   changeStatus(todo: Todo){
    this.todos?.map( singleTodo => {
      if (singleTodo.id == todo.id) {
        todo.isCompleted = !todo.isCompleted;
      }
    } );
   }

   deleteTodo(todo: Todo){
     const indexofTodo  = this.todos?.findIndex(
       (currentObj) => currentObj.id === todo.id
     ) ;
     this.todos?.splice(indexofTodo, 1);  //Error showing here for indexofTodo
   }


}

1 个答案:

答案 0 :(得分:0)

indexofTodo 的类型为 number | undefined,因为 this.todos?.findIndex 可以返回一个数字或 undefined(如果 this.todosundefined)。但是您不能使用 splice 调用 undefined。您可以通过类型检查修复它:

if (indexofTodo !== undefined) this.todos?.splice(indexofTodo, 1);

或者你可以替换

todos: Todo[] | undefined;

todos: Todo[];

意思是一样的。