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

TypeScript下运行react-beautiful-dnd多列拖拽示例出现TS编译错误如何解决?

两个报错均为TypeScript静态类型检查对不确定索引访问的限制,修复方案如下:

错误1修复(result[droppableSource.droppableId] = sourceClone; 行报错)

问题根因:初始化的result是空对象{},TypeScript无法识别该对象支持字符串类型的key作为索引。
修改move函数内的代码:

  1. 将空对象的声明改为断言为IMoveResult类型,替换原有const result = {};
const result = {} as IMoveResult;
  1. 可选优化:将move函数的返回类型从IMoveResult | any简化为IMoveResult,此时返回值类型完全匹配定义。

错误2修复(return this.state[this.id2List[id]]; 行报错)

问题根因:this.id2List[id]返回值为普通字符串,TypeScript无法确认该字符串是IAppState接口的合法属性名。
任选以下一种方案修复即可:

方案1:给id2List增加类型约束(更推荐,类型覆盖更完整)

修改类内id2List的定义:

public id2List: Record<string, keyof IAppState> = {
  droppable: 'items',
  droppable2: 'selected'
};

方案2:索引时增加类型断言

修改getList方法的返回语句:

public getList (id:string):Item[] {
  return this.state[this.id2List[id] as keyof IAppState];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:06:04