Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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',
  },
];
  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?

like image 747
Phillipp Avatar asked Jul 31 '26 13:07

Phillipp


1 Answers

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);
like image 61
gilamran Avatar answered Aug 02 '26 02:08

gilamran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!