繁体   English   中英

打字稿类型转换为D3.js

[英]Typescript typecast with D3.js

我正在使用此处显示的示例D3图表。 我在这里声明了以下数据对象:

interface ID3Data {
  age: string,
  population: number
}

const data: ID3Data[] = [
  { age: "<5", population: 2704659 },
  { age: "5-13", population: 4499890 }
]

然后被消费在以下:

const pie = d3.pie()
              .value(function(d: any) { return d.population; });

const arc = g.selectAll(".arc")
             .data(pie(data)) // ->>> Specifically this part of the code

哪会产生这个错误:

TypeScript error: Argument of type 'ID3Data[]' is not assignable to parameter of type '(number | { valueOf(): number; })[]'.
  Type 'ID3Data' is not assignable to type 'number | { valueOf(): number; }'.
    Type 'ID3Data' is not assignable to type '{ valueOf(): number; }'.
      Types of property 'valueOf' are incompatible.
        Type '() => Object' is not assignable to type '() => number'.
          Type 'Object' is not assignable to type 'number'.  TS2345

因为很明显d3.pie().value()会消耗一种非常特殊类型的输入数据,所以我接收编译错误的错误是什么? 由于D3的值函数是特定于它的库...我可以在我的打字稿代码中覆盖它吗?

这是有问题的代码:

const pie = d3.pie()
              .value(function(d: any) { return d.population; });

由于您没有指定要传递给生成器的数据类型,因此TypeScript编译器将使用以下类型定义

export function pie(): Pie<any, number | { valueOf(): number }>;

这会导致您目睹的错误,因为您的类型ID3Data显然与number | { valueOf(): number }不匹配 number | { valueOf(): number }

幸运的是,通过使用泛型来创建生成器时传递正确类型的数据可以很容易地解决这个问题:

const pie = d3.pie<ID3Data>()
  .value(function(d) { return d.population; });   // Do not use any for the parameter!

这将使编译器使用以下类型定义

export function pie<Datum>(): Pie<any, Datum>;

如您所见,现在将Datum类型传递给Pie接口类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM