首页 > 解决方案 > Angular:类型的参数不可分配给..的参数,并且类型中缺少属性“id”

问题描述

感谢您查看这个问题。我对 Angular 很陌生,我有一个我无法弄清楚的问题。我正在做一件小事,为了练习,添加带有复选框的文本。但是,我还没有做到这一点。它失败并出现以下错误:

Eerror TS2345: Argument of type '{ title: string; done: false; }' is not assignable to parameter of type '{ id: number; title: string; done: boolean; }'.

Property 'id' is missing in type '{ title: string; done: false; }'.

代码是 task-list.component.ts

这是我的 ts 文件。如果您需要更多信息,请告诉我。我现在一头雾水!谢谢

import {Component, ViewEncapsulation} from '@angular/core';

@Component({
  selector: 'mac-task-list',
  templateUrl: './task-list.component.html',
  encapsulation: ViewEncapsulation.None
})
export class TaskListComponent {
  tasks = [
    {id: 1, title: 'Task 1', done: false},
    {id: 2, title: 'Task 2', done: true}
  ];

  addTask(title: string) { // fails here
    this.tasks.push({
      title, done: false
    });
  }
}

标签: angularcomponents

解决方案


您需要添加缺少的道具:

出于测试目的,创建一个计数器来生成一个 id 值:

countId = 0;
//...

addTask(title: string) { // fails here
    this.tasks.push({
      id: this.countId++,
      title, done: false
    });
  }

否则将 id 属性声明为可选属性。


推荐阅读