使用d3.js和TypeScript绘制饼图时的编译错误

时间:2015-10-13 16:45:54

标签: javascript d3.js svg typescript

我正在尝试使用d3.js库和TypeScript绘制饼图。我有以下代码:

"use strict";
module Chart {
  export class chart {

    private chart: d3.Selection<string>;
    private width: number;
    private height: number;
    private radius: number;
    private donutWidth: number;
    private dataset: { label: string, count: number }[];
    private color: d3.scale.Ordinal<string, string>;

    constructor(container: any) {
      this.width = 360;
      this.height = 360;
      this.radius = Math.min(this.width, this.height) / 2;
      this.donutWidth = 75;

      this.dataset = [
        { label: 'Road', count: 5500 },
        { label: 'Bridge', count: 8800 },
        { label: 'Tunnel', count: 225 },
      ];

      this.color = d3.scale.category10();

      this.init(container);

    }

    private init(container) {
      this.chart = d3.select(container).append('svg')
        .attr('width', this.width)
        .attr('height', this.height)
        .append('g')
        .attr('transform', 'translate(' + (this.width / 2) +
        ',' + (this.height / 2) + ')');
    }

    draw() {

      var arc = d3.svg.arc()
        .innerRadius(this.radius - this.donutWidth)  // NEW
        .outerRadius(this.radius);

      var pie = d3.layout.pie()
        .sort(null);

      var path = this.chart.selectAll('path')
        .data(pie(this.dataset.map(function(n) {
          return n.count;
        })))
        .enter()
        .append('path')
        .attr('d', arc)
        .attr('fill', function(d, i) {
          return Math.random();
        });
    }

  }
}

代码无法编译并显示错误:

 Argument of type 'Arc<Arc>' is not assignable to parameter of type '(datum: Arc<number>, index: number, outerIndex: number) => string | number | boolean'.
>>   Types of parameters 'd' and 'datum' are incompatible.
>>     Type 'Arc' is not assignable to type 'Arc<number>'.
>>       Property 'value' is missing in type 'Arc'.   

当我尝试将d属性添加到我的svg上的每个path元素时,出现编译错误:

var path = this.chart.selectAll('path')
        .data(pie(this.dataset.map(function(n) {
          return n.count;
        })))
        .enter()
        .append('path')
        .attr('d', arc)
        .attr('fill', function(d, i) {
          return Math.random();
        });

根据文档,弧是“既是对象又是函数”。我看到我可以通过调用arc(datum[, index])来访问它,只需硬编码arc[0]即可。当我这样做时,我的编译错误消失了,但svg中每个d元素的path属性都丢失了,我最终得到了一个svg:

    <svg height="360" width="360">
      <g transform="translate(180,180)">
         <path fill="0.35327279710072423"></path>
         <path fill="0.6333000506884181"></path>
         <path fill="0.9358429045830001"></path>
      </g>
    </svg>

我已经将代码作为纯JavaScript运行而没有任何问题。

3 个答案:

答案 0 :(得分:15)

尝试替换

.attr('d', arc)   

.attr('d', <any>arc)  

这会在我的计算机上隐藏编译器错误,但如果确实有效......好吧,我不知道。

我对此问题的理解是,您提供.data函数的number值,而TypeScript编译器期望.attr也包含一个数字,但您提供的是arc

答案 1 :(得分:7)

来到这里是因为我在D3 v5中也遇到了同样的问题!

解决方案:使用PieArcDatum界面(我觉得这个名字很奇怪!)

详细信息:

import { PieArcDatum } from 'd3-shape';

... 

type Population = { time: string, population: number; };

...

const svg = element.append("g")
    .attr("transform", `translate(${300}, ${160})`)
;

const pie = d3.pie<Population>()
    .sort(null)
    .value((record) => record.population);

const path = d3.arc<PieArcDatum<Population>>()
    .innerRadius(0)
    .outerRadius(150)
;

// Beim selectAll kommt eine leere Selection zurück da es noch keinen Circle gibt
const data = pie(worldPopulation);
const arch = svg.selectAll(".arc")
    .data(data)
    .enter()
    .append("g")
        .attr("class", "arc")
;

arch.append('path')
    .attr("d", path)
;


旁注:我正在使用WebStorm,WS无法找到(自动导入)PieArcDatum-我必须手动将其导入...

答案 2 :(得分:5)

虽然使用<any>可以避免编译错误,但它首先会破坏进行类型检查的目的。经过the d3.d.ts definition for the Arc layout的大量试验和错误以及质量时间之后,我想出了如何使类型排成一行:

function draw() {

    let arc = d3.svg.arc<d3.layout.pie.Arc<number>>()
        .innerRadius(this.radius - this.donutWidth)
        .outerRadius(this.radius);

    let pie = d3.layout.pie().sort(null);

    let tfx = (d: d3.layout.pie.Arc<number>): string => `translate(${arc.centroid(d)})`);

    // create a group for the pie chart
    let g = this.chart.selectAll('g')
        .data(pie(this.dataset.map(n => n.count)))
        .enter().append('g');

    // add pie sections
    g.append('path').attr('d', arc);

    // add labels
    g.append('text').attr('transform', tfx).text(d => d.data.label);
}

除了原始问题之外,我还展示了如何在饼图中添加标签并保持Typescript的强类型。请注意,此实现利用the alternate constructor d3.svg.arc<T>(): Arc<T>允许您为arc部分指定类型。

更新

上面的代码假设传递的data是一个数字数组。如果您查看代码(特别是访问者n => n.countd => d.data.label),则显然不是。这些访问器也具有隐式any类型,即(n: any) => n.count。如果n碰巧是没有count属性的对象,则可能会抛出运行时错误。这是一个重写,使data的形状更明确:

interface Datum {
    label: string;
    count: number;
}

function draw() {

    // specify Datum as shape of data
    let arc = d3.svg.arc<d3.layout.pie.Arc<Datum>>()
        .innerRadius(this.radius - this.donutWidth)
        .outerRadius(this.radius);

    // notice accessor receives d of type Datum
    let pie = d3.layout.pie<Datum>().sort(null).value((d: Datum):number => d.count);

    // note input to all .attr() and .text() functions
    // will be of type d3.layout.pie.Arc<Datum>
    let tfx  = (d: d3.layout.pie.Arc<Datum>): string => `translate(${arc.centroid(d)})`;
    let text = (d: d3.layout.pie.Arc<Datum>): string => d.data.category;

    // create a group for the pie chart
    let g = this.chart.selectAll('g')
        .data(pie(data))
        .enter().append('g');

    // add pie sections
    g.append('path').attr('d', arc);

    // add labels
    g.append('text').attr('transform', tfx).text(text);
}

在第二个版本中,不再存在任何隐式any类型。另一件需要注意的是,接口的名称Datum是任意的。您可以将该界面命名为您想要的任何名称,但只需要小心地将对Datum的所有引用更改为您选择的任何更合适的名称。