Avatar ·

如何在TypeScript中删除数组元素?详细指南

大家好!我是TypeScript新手,遇到了删除数组元素的问题。我翻了很多论坛,但还是不明白在TypeScript中如何正确地根据类型进行删除。 我有一个简单的任务列表接口: ```typescript interface Task { id: number; title: string; completed: boolean; } ``` 以及一个任务数组: ```typescript const tasks: Task[] = [ { id: 1, title: '买牛奶', completed: false }, { id: 2, title: '做作业', completed: true }, { id: 3, title: '给朋友打电话', completed: false } ]; ``` 我想根据id删除任务。在JavaScript中,我通常使用`splice()`或`filter()`,但在TypeScript中会出现类型错误。例如,当我写: ```typescript const index = tasks.findIndex(task => task.id === 2); if (index !== -1) { tasks.splice(index, 1); } ``` TypeScript报错说`tasks`是`const`,我不能修改它。而如果我尝试使用`filter()`: