d3 v4 TypeScript类型

时间:2016-11-23 04:56:22

标签: d3.js typescript typescript-typings

我正在整理一个小型d3项目,因为它非常复杂,我想使用TypeScript使一些开发更简单,更不容易出错。

我正在使用d3 v4。我以前认为我之前使用的是错误的类型定义文件,但是我很久没遇到任何问题,直到它最终抱怨d3不包含scaleLinear()的定义。

我已经转移到我认为正确的定义文件, 具有d3.scaleLinear()的定义,但是现在我的大量变量都有无效的类型。< / p>

以下是一些例子:

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>

我已经尝试将鼠标悬停在创建例如<g>元素的调用上,以确切了解签名应该是什么,但它实际上是, any any any>

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

谢谢。

1 个答案:

答案 0 :(得分:8)

你的问题究竟在哪里我看不到。这是可能的:

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)