使用solid-dnd TSX示例代码遇ts(2322)类型错误求助
我在TSX中使用Solid-DND的垂直可排序列表示例时,遇到两个TS(2322)类型错误:
第一个错误
(property) use:sortable: true
Type '{ children: any; "use:sortable": true; class: string; classList: { "opacity-25": boolean; "transition-transform": boolean; }; }' is not assignable to type 'HTMLAttributes
'. Property 'use:sortable' does not exist on type 'HTMLAttributes
'.ts(2322)
第二个错误
Type 'Element' is not assignable to type '(Element | ((activeDraggable: Draggable) => Element)) & Element'.
Type 'number' is not assignable to type '(Element | ((activeDraggable: Draggable) => Element)) & Element'.ts(2322)
drag-overlay.d.ts(4, 5): The expected type comes from property 'children' which is declared here on type 'IntrinsicAttributes & DragOverlayProps & { children?: Element; }'
我尝试扩展HTMLAttributes接口来解决第一个错误,但未生效:
interface HTMLAttributes<HTMLDivElement> { "use:sortable": boolean }
修复方案
第一个错误的修复
你扩展接口的方式不符合Solid JSX类型规范,use:sortable是Solid的指令属性,需要在Solid的JSX命名空间下扩展HTMLAttributes类型:
- 在项目中创建或修改一个
.d.ts类型声明文件(比如solid-dnd-extension.d.ts) - 写入以下代码:
import type { HTMLAttributes } from 'solid-js'; declare module 'solid-js' { namespace JSX { interface HTMLAttributes<T> { 'use:sortable'?: boolean; } } }
- 确保
tsconfig.json的include数组包含该.d.ts文件,比如:
{ "include": ["src/**/*", "*.d.ts"] }
第二个错误的修复
这个错误是因为DragOverlay的children属性仅接受Element对象或接收activeDraggable参数并返回Element的函数,但你传入了数值类型(大概率是渲染列表时误用了数组索引等数值)。
正确写法示例:
<DragOverlay> {(activeDraggable) => { if (!activeDraggable) return null; // 根据activeDraggable的数据渲染拖拽预览元素 return <div class="drag-preview">{activeDraggable.data.itemName}</div>; }} </DragOverlay>
如果直接传入Element,要确保传入的不是数值、字符串等非Element类型值。
内容的提问来源于stack exchange,提问作者SmoothTraderKen

