TypeScript中因缺少类型注解导致"this"隐式具有"any"类型的错误
你好!我开始学习TypeScript时遇到了一个无法解决的错误。我有一个简单的类来管理任务列表:
```typescript
class TaskList {
tasks: string[] = [];
addTask(task: string) {
this.tasks.push(task);
console.log(`Added: ${task}`);
}
printTasks() {
this.tasks.forEach(function(task) {
console.log(`${task} - added by ${this.name}`);
});
}
}
const myList = new TaskList();
myList.addTask("Learn TypeScript");
myList.printTasks();
```
当我编译这段代码时,收到错误:
```
'this' implicitly has type 'any' because it does not have a type annotation
```
错误指向`forEach`方法内部的`console.log(`${task} - added by ${this.name}`);`这一行。我明白`this`在callback函数中失去了类的上下文,但不知道如何正确修复。我尝试使用箭头函数,但出现了另一个错误——`this.name`不存在于