d3 v5 scaleThreshold 不接受范围内的字符串颜色数组?

gpb*_*lio 1 d3.js typescript

这是我的代码:

var legendThreshold = d3
      .scaleThreshold()
      .domain(
        (function(min, max, count) {
          var array = [];
          var step = (max - min) / count;
          var base = min;
          for (var i = 1; i < count; i++) {
            array.push(base + i * step);
          }
          return array;
        })(minTemp, maxTemp, legendColors.length)
      )
      .range(["red", "white", "green"]);
Run Code Online (Sandbox Code Playgroud)

我在范围上遇到错误:

“string[]”类型的参数不可分配给“readonly number[]”类型的参数

但如果您查看此链接中的示例,我相信我的代码应该是正确的。我该如何解决?

wen*_*jun 6

看起来您正在使用 TypeScript。

您可能需要提供泛型才能d3.scaleThreshold()使其接受字符串。

正如D3.js 的 DefinelyTyped TypeScript 类型定义中提到的,

  • 构建新的阈值尺度。域和值域必须根据相应泛型的类型来设置。
    • 第一个泛型对应于域值的数据类型。
    • 第二个泛型对应于范围值的数据类型。

由于您对 和 都使用字符串domainrange因此我们可以将这两种类型指定为string

d3.scaleThreshold<string, string>().domain().range()
Run Code Online (Sandbox Code Playgroud)

参考