我正在尝试在 React 应用程序(使用 TypeScript)中复制这个d3 热图。但是,下面的代码让我很头疼:
const colorScale = d3.scaleQuantile()
.domain([0, buckets - 1, d3.max(data, (d: any) => parseInt(d.value))])
.range(colors);
Run Code Online (Sandbox Code Playgroud)
colors
用红色下划线表示,提示如下错误:
类型 'string' 不能分配给类型 'number'
我想知道如何缓解这个问题。
根据使用的 scale 模块的版本不同,答案会有细微的差别。无论如何,主要解决方案不受此影响并且适用于所有版本。
您链接到的示例使用 D3 v4,它取决于d3-scale 模块v1。
如果您查看类型定义,d3.scaleQuantile()
您会注意到它的创建有两个定义:
/**
* Constructs a new quantile scale with an empty domain and an empty range.
* The quantile scale is invalid until both a domain and range are specified.
*/
export function scaleQuantile(): ScaleQuantile<number>;
/**
* Constructs a new quantile scale with an empty domain and an empty range.
* The quantile scale is invalid until both a domain and range are specified.
*
* The generic corresponds to the data type of range elements.
*/
export function scaleQuantile<Range>(): ScaleQuantile<Range>;
Run Code Online (Sandbox Code Playgroud)
因为您没有指定泛型Range
类型参数,编译器默认为第一个定义,将范围的类型推断为 a number
,因此,包含字符串的范围的错误。
但是,通过明确指定比例范围的类型,这可以很容易地解决,即string
:
const colorScale = d3.scaleQuantile<string>() // Specify the type of the scale's range: <string>.
.domain([0, buckets - 1, d3.max(data, (d: any) => parseInt(d.value))])
.range(colors);
Run Code Online (Sandbox Code Playgroud)
D3 v5使用d3-scale 模块的第 2 版,仅对 scale 的类型定义进行了微小的更改。
为独立模块使用 d3-scale 的类型定义时要小心,因为它们是为模块的版本 2.1.2 创建的。在撰写本文时,最新的独立版本是 3.1.0,其中包含对 API 的重大更改!唉,该版本没有可用的类型定义。