D3 + Typescript: pie() does not accept an array of objects

问题: I have the following code: public data = [ { value: 61, color: 'orange', }, { value: 29, color: 'white', }, { value: 10, color: 'blue',...

问题:

I have the following code:

public data = [
  {
    value: 61,
    color: 'orange',
  },
  {
    value: 29,
    color: 'white',
  },
  {
    value: 10,
    color: 'blue',
  },
];
  public pie = d3
    .pie()
    .padAngle(0)
    .value((d: any) => d.value);
const arcs = this.pie(this.data);

Which is basically the outcome of some of the various tutorials about building a donut chart with d3js.

Now I would like to add a custom interface for the items in the data array and also properly type the d parameter in the .value() function.

The problem is, that the @types/d3 package defines the expected data array as number[] and the d parameter as number.

Which means that I cannot use a custom interface for the data items. The typings package for D3 seems to be wrong in this case because all the tutorials I've read do it this way and the code works just fine.

What are my options in this case? Are there any workarounds? Can I override the typings that get into my way?


回答1:

d3's pie accepts a generic just for that.

Here's how to solve this:

interface IData {
  value: number;
  color: string;
}

const data: IData[] = [
  {
    value: 61,
    color: 'orange',
  },
  {
    value: 29,
    color: 'white',
  },
  {
    value: 10,
    color: 'blue',
  },
];

const pie = d3
  .pie<IData>()
  .padAngle(0)
  .value(d => d.value);

const arcs = pie(data);
  • 发表于 2019-03-07 15:41
  • 阅读 ( 174 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除