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

使用@hello-pangea/dnd自定义type属性遇TS类型错误及部署问题

解决@hello-pangea/dnd自定义Draggable属性的TypeScript报错及部署问题

下面是几种可行的解决方案,从临时绕过到规范适配都有覆盖:

方法一:临时用类型断言快速绕过

如果只是临时调试,可直接通过类型断言或注释跳过TS检查:

<Draggable 
  draggableId={section.id} 
  index={index} 
  // @ts-ignore 直接忽略类型检查
  type="section"
>

或者用更严谨的类型断言:

<Draggable 
  draggableId={section.id} 
  index={index} 
  {...({ type: "section" } as unknown as Partial<DraggableProps>)}
>

注意:此方法仅适合临时场景,不推荐长期使用,会失去TS的类型校验能力。

方法二:封装自定义Draggable组件(推荐)

自己封装一层组件,扩展原Draggable的Props类型,彻底解决类型问题,且部署不受依赖更新影响:

import { Draggable, DraggableProps } from '@hello-pangea/dnd';

// 扩展原Props,添加自定义type属性
interface CustomDraggableProps extends DraggableProps {
  type?: string;
}

export const CustomDraggable = ({ type, ...props }: CustomDraggableProps) => {
  // 若需要在拖拽回调中获取type,可通过draggableId关联存储
  // 比如提前维护一个draggableId到type的映射表
  return <Draggable {...props} />;
};

使用时直接替换原Draggable:

<CustomDraggable draggableId={section.id} index={index} type="section">
  {(provided) => (
    <div {...provided.draggableProps} {...provided.dragHandleProps}>
      {/* 拖拽项内容 */}
    </div>
  )}
</CustomDraggable>

在拖拽结束的回调中,通过draggableId从映射表中获取type:

// 提前维护映射表
const draggableTypeMap = new Map<string, string>();
draggableTypeMap.set(section.id, "section");

// 在onDragEnd回调中使用
const handleDragEnd = (result) => {
  const type = draggableTypeMap.get(result.draggableId);
  if (type === "section") {
    handleSectionDragDrop(result.source, result.destination, updatedSections);
  } else {
    handleTaskDragDrop(result.source, result.destination, updatedSections);
  }
};

方法三:TypeScript模块扩充(最规范)

通过TS的模块扩充能力,直接扩展原库的类型声明,无需封装组件:

  1. 在项目根目录或src下创建类型声明文件@hello-pangea-dnd.d.ts:
import '@hello-pangea/dnd';

declare module '@hello-pangea/dnd' {
  interface DraggableProps {
    type?: string;
  }
}
  1. 修改tsconfig.json,确保该声明文件被TS识别:
{
  "compilerOptions": {
    "typeRoots": ["./node_modules/@types", "./src/types"]
  },
  "include": ["src/**/*", "./@hello-pangea-dnd.d.ts"]
}

之后TS会自动识别扩展的type属性,无需修改依赖包文件,部署时也不会因依赖更新失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 06:32:50