Ozz*_*zah 5 d3.js typescript typescript-typings
我正在组建一个小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>;
Run Code Online (Sandbox Code Playgroud)
我曾经像这样创建这些:
this.SVGElement = d3.Select("body").append("svg");
this.SVGTitleArea = <d3.Selection<SVGGElement>>this.SVGElement.append("g");
Run Code Online (Sandbox Code Playgroud)
等等
我还有许多函数可以呈现图形的不同组件:
public RenderTitle() : d3.Selection<SVGGElement> {
this.SVGTitleArea = <d3.Selection<SVGGElement>>this.SVGElement.append("g");
// Do stuff here
return this.SVGTitleArea;
}
Run Code Online (Sandbox Code Playgroud)
自从转移到可能正确的打字文件后,它现在抱怨该d3.Selection类型需要4种类型:
interface Selection<GElement extends Element | EnterElement | Window, Datum, PElement extends Element | EnterElement | Window, PDatum>
Run Code Online (Sandbox Code Playgroud)
现在,我知道它不理想,我更喜欢更强的打字,但我设法至少修复了关于变量定义的错误:
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>;
Run Code Online (Sandbox Code Playgroud)
但我不能对渲染函数做同样的事情:
public RenderTitle() : d3.Selection<SVGGElement, any, any, any>
Run Code Online (Sandbox Code Playgroud)
我已经尝试将鼠标悬停在创建的<g>元素上,例如,该元素可以确切地查看签名应该是什么,但它实际上给出了, any any any>.
这是我最好的选择?有没有一种简单的方法来修复这些类型?我应该把它们全部留下来any吗?我应该降级到d3 v3吗?我应该继续使用v4并放弃TypeScript吗?
谢谢.
究竟你的问题在哪里,我没有看到.这个有可能:
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)
Run Code Online (Sandbox Code Playgroud)