【发布时间】:2021-09-02 22:31:44
【问题描述】:
我正在学习 TypeScript。
todoItem.ts的内容:
export class TodoItem {
constructor(
public id: number,
public task: string,
public complete: boolean = false
) {}
printDetails(): void {
console.log(
`${this.id}\t${this.task} ${this.complete ? "\t(complete)" : ""}`
);
}
}
todoCollection.ts的内容:
import { TodoItem } from "./todoItem";
export class TodoCollection {
private nextId: number = 1;
constructor(public userName: string, public todoItems: TodoItem[] = []) {}
addTodo(task: string): number {
while (this.getTodoById(this.nextId)) {
this.nextId++;
}
this.todoItems.push(new TodoItem(this.nextId, task));
return this.nextId;
}
getTodoById(id: number): TodoItem {
return this.todoItems.find((item) => item.id === id);
}
}
使用tsc 编译时,出现以下错误:
src/todoCollection.ts:17:5 - 错误 TS2322:类型 'TodoItem |不明确的' 不可分配给类型“TodoItem”。类型“未定义”不是 可分配给类型“TodoItem”。
17 return this.todoItems.find((item) => item.id === id); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~
发现 1 个错误。
问题
如何解决这个错误?我真的不知道,因为我无法发现任何特殊性。一切看起来都很好。
【问题讨论】:
标签: javascript typescript