d3 / d3-hierarchy

2D layout algorithms for visualizing hierarchical data.
https://d3js.org/d3-hierarchy
ISC License
1.14k stars 314 forks source link

How can I handle the ts error "Type 'number | undefined' is not assignable to type 'number'." ? #168

Closed takeItIzzy closed 4 years ago

takeItIzzy commented 4 years ago
const regions =
  data &&
  d3
    .hierarchy('data')
    .sum((d) => 1)
    .sort((a, b) => b.value - a.value);

The callback of sort() will throw an error Object is possibly 'undefined'. when I use typeScript, and if I add a condition like this:

const regions =
  data &&
  d3
    .hierarchy('data')
    .sum((d) => 1)
    .sort((a, b) => {
      if (a.value && b.value) {
        return b.value - a.value;
      }
    });

It'll say Type 'number | undefined' is not assignable to type 'number'. How can I handle with it?

Fil commented 4 years ago

Please address D3 typescript queries to https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/d3

PS: I am surprised by the quotes around 'data' in the hierarchy() call.