发生“无法读取未定义的属性'xxx'”错误

时间:2019-06-05 02:28:36

标签: javascript typescript

我在TypeScript中实现了以下代码。

class Task {
    text: string
    userId: string

    constructor(text: string, userId: string) {
        this.text = text;
        this.userId = userId;
    }
}

class TmpTask {
    userId: string;
    tasks: Task[];

    constructor(userId: string) {
        this.userId = userId;
        this.tasks = [];
    }
}

const tasks: Task[] = [];
tasks.push(new Task('Send a mail now!!', 'bob'));
const tmpTasks: TmpTask[] = [];


for (let task of tasks) {
    console.log("task: ", task);

    const index = tmpTasks.findIndex( (_tmpTask, _index, _tmpTasks) => {
        return _tmpTask.userId === task.userId;
    });
    tmpTasks[index].tasks.push(task);
}
console.log("tmpTasks: ", tmpTasks);

此代码运行时,将导致以下错误。

Uncaught TypeError: Cannot read property 'tasks' of undefined
    at _loop_1 (<anonymous>:23:21)
    at <anonymous>:27:5
    at HTMLButtonElement.excuteButton.onclick (http://www.typescriptlang.org/play/playground.js:247)

我不知道如何解决。

您能给我任何建议吗?

0 个答案:

没有答案