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

@types/d3-selection 是否存在类型定义Bug?还是我理解有误?

D3 Selection方法TypeScript返回类型疑惑及提交建议

我在使用D3和TypeScript时,对Selection各类方法的返回类型感到困惑。当前Selection接口定义如下:

/**
 * A D3 Selection of elements.
 *
 * The first generic "GElement" refers to the type of the selected element(s).
 * The second generic "Datum" refers to the type of the datum of a selected element(s).
 * The third generic "PElement" refers to the type of the parent element(s) in the D3 selection.
 * The fourth generic "PDatum" refers to the type of the datum of the parent element(s).
 */
export interface Selection<GElement extends BaseType, Datum, PElement extends BaseType, PDatum> {

该接口中多个返回子选择的方法类型定义疑似错误,仅两个方法符合我的理解:

正确示例:selectAll

selectAll<DescElement extends BaseType, OldDatum>(selector: string)
: Selection<DescElement, OldDatum, GElement, Datum>;

错误示例:select

select<DescElement extends BaseType>(selector: string)
: Selection<DescElement, Datum, PElement, PDatum>;

错误在于该方法未将*自身(当前Selection)*的类型传入子选择的类型参数,而是传入了父元素的类型和数据。

受影响的方法列表

  • select // incorrect
  • selectChild // incorrect
  • append // incorrect
  • insert // incorrect

注:selectAll、selectChildren的类型定义符合预期。

由于D3类型每周下载量达百万次,我不确定是自己理解有误,还是确实存在问题。

关于提交PR的说明

D3的TypeScript类型定义托管在DefinitelyTyped仓库,你应该向DefinitelyTyped提交PR。提交前建议先搜索仓库的issue列表,确认是否已有类似问题被提出,避免重复工作;如果没有,可以先开issue讨论你的发现,确认理解无误后再提交PR。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 12:20:18