I am learning TypeScript.
The contents of 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)" : ""}`
);
}
}
The contents of 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);
}
}
When compiling with tsc
, I get the following error:
src/todoCollection.ts:17:5 - error TS2322: Type 'TodoItem | undefined' is not assignable to type 'TodoItem'. Type 'undefined' is not assignable to type 'TodoItem'.
17 return this.todoItems.find((item) => item.id === id); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Found 1 error.
Question
How to fix this error? I really have no idea because I cannot spot any peculiarity. Everything looks fine.