Typescript + React + D3v4:“对象可能是'未定义'错误,在d3 scaleBand上

问题描述 投票:1回答:2

如何解析在[['yScale'处发生的Object is possibly 'undefined' error

interface IData { id: string; phone_number: string, } const data : IData[] const devices = data.map((d) => d.phone_number) const yScale = d3.scaleBand() .range([0, 30 * devices.length]) .domain(devices) const yAccessor = (d: string) => yScale(d)
我认为这是发生的,因为打字稿认为d3的scaleBand将返回未定义的,因为'devices'变量是任何空数组。当我将鼠标悬停在IDE中的“设备”上时,它显示为'let devices: string[]'。但是,处于初始状态的“设备”为空(因为尚未提交搜索)。如果“设备”已包含元素列表,则不会发生此错误。

这里是d3标尺的type definitions

export interface ScaleBand<Domain extends { toString(): string }> { /** * Given a value in the input domain, returns the start of the corresponding band derived from the output range. * If the given value is not in the scale’s domain, returns undefined. * * @param x A value from the domain. */ (x: Domain): number | undefined; ... }

typescript d3.js
2个回答
0
投票
鉴于data可能为空数组,可以在调用yScale之前进行检查以确保data不为空。

if (!data.length) { return; } const devices = data.map((d) => d.phone_number) const yScale = d3.scaleBand() .range([0, 30 * devices.length]) .domain(devices)

如果数据为空数组,这将导致钩子/方法中的早期返回。    

0
投票
一种可能的解决方案是允许在像tsconfig这样的打字稿编译器设置中使用未定义/空值。但是我不确定是否建议这样做。
© www.soinside.com 2019 - 2024. All rights reserved.