You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript报错:'any'类型参数无法赋值给'never'类型参数

解决TypeScript错误:'Argument of type 'any' is not assignable to parameter of type 'never''

问题原因

你定义的categorizedToDoList类型是{ [key: string]: []},TypeScript会把空数组[]推断为never[]类型——这是一种只能包含never值的数组,而你试图往里面push普通的todo对象,自然会触发类型不匹配的错误。另外item: any的写法也绕过了TypeScript的类型检查,不够严谨。

修复方案

  1. 明确Todo类型:先定义todo项的接口,让类型系统有明确的参照
  2. 修正categorizedToDoList的类型:指定其值为Todo类型的数组,而非空数组
  3. 移除不必要的any注解:让TypeScript自动推断item的类型

修复后的代码

// 定义Todo项的类型
interface Todo {
  todo: string;
  category: string;
}

// 修正类型为{ [key: string]: Todo[] }
categorizedToDoList: { [key: string]: Todo[] } = {};
categories = ["BLA", "BLA2", "BLA3", "BLA4"];
// 这里自动推断为Todo[]类型
todoList: Todo[] = [ 
 { todo: "first Item", category: "category1"},
 { todo: "Second Item", category: "category2"},
 { todo: "Third Item", category: "category2"}    
];

categorisedTodo() {
   this.categories.forEach(key => {
     this.categorizedToDoList[key] = [];
     // 移除item: any,TypeScript会自动推断为Todo类型
     this.todoList.forEach(item => {        
       if (key === item.category) { 
         this.categorizedToDoList[key].push(item);
       }
     });
   });    
 }

额外优化(可选)

可以用Array.prototype.filter简化循环逻辑,让代码更简洁:

categorisedTodo() {
  this.categories.forEach(key => {
    this.categorizedToDoList[key] = this.todoList.filter(item => item.category === key);
  });
}

内容的提问来源于stack exchange,提问作者user11586200

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 15:46:14