【问题标题】:d3 v4 TypeScript typesd3 v4 TypeScript 类型
【发布时间】:2017-04-06 23:36:02
【问题描述】:

我正在整理一个小 d3 项目,由于它相当复杂,我想使用 TypeScript 使一些开发更简单,更不容易出错。

我正在使用 d3 v4。我想我之前使用了错误的类型定义文件,但是很长一段时间我都没有遇到任何问题,直到它最终抱怨d3不包含scaleLinear()的定义。

我已经转移到我认为正确的定义文件,确实有一个d3.scaleLinear() 的定义,但是现在我的大量变量的类型无效。

这里有一些例子:

public SVGElement    : d3.Selection<SVGElement>;
public SVGTitleArea  : d3.Selection<SVGGElement>;
public SVGLegendArea : d3.Selection<SVGGElement>;
public SVGXAxisArea  : d3.Selection<SVGGElement>;
public SVGYAxisArea  : d3.Selection<SVGGElement>;
public SVGChartArea  : d3.Selection<SVGGElement>;

我以前是这样创建的:

this.SVGElement = d3.Select("body").append("svg");
this.SVGTitleArea = <d3.Selection<SVGGElement>>this.SVGElement.append("g");

等等

我还有一些函数可以渲染图表的不同组件:

public RenderTitle() : d3.Selection<SVGGElement> {
  this.SVGTitleArea = <d3.Selection<SVGGElement>>this.SVGElement.append("g");

  // Do stuff here

  return this.SVGTitleArea;
}

自从移到可能正确的类型文件后,它现在抱怨 d3.Selection 类型需要 4 种类型:

interface Selection<GElement extends Element | EnterElement | Window, Datum, PElement extends Element | EnterElement | Window, PDatum>

现在,我知道这并不理想,我更喜欢更强大的类型,但我已经设法至少修复了与变量定义有关的错误:

public SVGElement    : d3.Selection<SVGElement, any, any, any>;
public SVGTitleArea  : d3.Selection<SVGGElement, any, any, any>;
public SVGLegendArea : d3.Selection<SVGGElement, any, any, any>;
public SVGXAxisArea  : d3.Selection<SVGGElement, any, any, any>;
public SVGYAxisArea  : d3.Selection<SVGGElement, any, any, any>;
public SVGChartArea  : d3.Selection<SVGGElement, any, any, any>;

但我不能对渲染函数做同样的事情:

public RenderTitle() : d3.Selection<SVGGElement, any, any, any>

我尝试将鼠标悬停在创建例如 &lt;g&gt; 元素的调用上,以查看确切的签名应该是什么,但它实际上给出了 , any any any&gt;

我最好的选择是什么?有没有一种简单的方法来修复这些类型?我应该将它们全部保留为any 吗?我应该降级到 d3 v3 吗?我应该继续使用 v4 并放弃 TypeScript 吗?

谢谢。

【问题讨论】:

    标签: d3.js typescript typescript-typings


    【解决方案1】:

    我看不到您的问题出在哪里。这是可能的:

    let mySelection : d3.Selection<SVGElement, {}, HTMLElement, any> = d3.selectAll<SVGElement, {}>('#line');
    function foo() : d3.Selection<SVGElement, {}, HTMLElement, any> {
      return mySelection.append<SVGElement>('g')
    }
    alert(foo().node().tagName)
    

    【讨论】:

    • 谢谢。 (1) Selection 变量定义的模板签名错误,(2) 我没有意识到您可以为函数调用分配特定类型,例如 gObj = mySelection.append&lt;SVGGElement&gt;("g");相反,我试图完成整个任务:gObj = &lt;d3.Selection&lt;SVGGElement, /*something*/, /*something*/, /*something*/&gt;&gt;mySelection.append("g")。谢谢,您的建议似乎奏效了。
    猜你喜欢
    • 2017-10-15
    • 1970-01-01
    • 2016-10-19
    • 2017-03-11
    • 2022-01-23
    • 2017-07-13
    • 2020-04-21
    • 2017-06-28
    • 2019-08-22
    相关资源
    最近更新 更多