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

Material Drag and Drop API中<T>的含义是什么?附createDrag返回示例

Material CDK Drag and Drop中的含义
return (<T>是TypeScript的**泛型类型参数**,在Material CDK的Drag and Drop API里,它用来定义拖拽操作关联的数据类型,让API在编译阶段就能完成类型校验,避免运行时的类型错误。

以`createDrag`为例,这个方法的<T>用来指定拖拽元素绑定的数据类型。比如你要拖拽的是用户对象数组,就可以把<T>设为`User`,这样在使用`dragStarted`、`dragEnded`这类拖拽回调时,拿到的拖拽数据会自动被推断为`User`类型,无需手动做类型转换。

简单代码示例:
```typescript
// 自定义业务数据类型
interface Task {
  id: number;
  title: string;
}

// 用泛型指定拖拽数据类型为Task
const dragRef = createDrag<Task>({
  item: { id: 1, title: '完成文档编写' },
  // 回调里的item会自动被推断为Task类型
  dragStarted: (event) => console.log('拖拽开始,数据:', event.item.title)
});
```

这种泛型设计让拖拽API能适配任意业务数据类型,同时保留TypeScript的类型安全特性。

内容的提问来源于stack exchange,提问作者Rezenalize)
相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 05:37:10