I am currently in the process of learning TypeScript.
Here is what's inside 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)" : ""}`
);
}
}
These are 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);
}
}
Upon compiling with tsc
, an error arises:
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); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An error has been detected.
Question
How should I go about resolving this error? This issue has got me stumped as everything seems correct on my end.