【问题标题】:Error: No overload matches this call. Overload 1 of 2错误:没有重载匹配此调用。重载 1 of 2
【发布时间】:2021-07-23 17:29:38
【问题描述】:

我在 Angular 12.1.1 中收到以下 typescript(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
   }


}

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

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

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

    或者你可以替换

    todos: Todo[] | undefined;
    

    todos: Todo[];
    

    意思是一样的。

    【讨论】:

    • 是的,通过将其替换为以下待办事项,它已解决: Todo[ ] ;谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 2022-12-30
    相关资源
    最近更新 更多