如何解决如何格式化 Y 轴以仅显示自然数?
我在格式 Y 轴上中继任务以仅显示自然数时遇到问题。在项目中,我使用 React awith Typescript 和 Nivo Rocks 库来创建图表(https://nivo.rocks/)。为了这个问题,我创建了沙箱:
https://codesandbox.io/s/scuqn?file=/src/App.tsx
我找到了设置格式的解决方案:
axisLeft={{
format: e => Math.floor(e) === e && e
}}
/>
但它仅适用于纯 js(无类型检查)。使用 TS 存在类型错误(带有“e:number”):
No overload matches this call.
Overload 1 of 2,'(props: LinesvgProps | Readonly<LinesvgProps>): ResponsiveLine',gave the following error.
Type '(e: number) => number | undefined' is not assignable to type 'string | TickFormatter | undefined'.
Type '(e: number) => number | undefined' is not assignable to type 'TickFormatter'.
Types of parameters 'e' and 'value' are incompatible.
Type 'string | number | Date' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.
Overload 2 of 2,'(props: LinesvgProps,context: any): ResponsiveLine',gave the following error.
Type '(e: number) => number | undefined' is not assignable to type 'string | TickFormatter | undefined'.
Type '(e: number) => number | undefined' is not assignable to type 'TickFormatter'.ts(2769)
我无法将类型与此解决方案匹配,也无法使用“任何”类型,我开始相信库创建者没有在他们的库中预测到这个问题;) 如果有人可以帮助我解决这些问题或提出另一种解决方案,我将不胜感激:)
解决方法
那是因为您的自定义函数的签名与库期望的签名不匹配。在这种情况下,您的函数应与 TickFormatter
的签名匹配:
export type TickFormatter = (value: number | string | Date) => string | number
如您所见,您的函数与库所期望的函数之间存在多种不兼容性。首先,您说您的值只能是一个数字,但库说 value
也可以是 string
甚至 Date
对象。其次,您的函数可以返回 undefined
,而库期望的函数只能返回 string
或 number
。
另外,正如您所说,在此处使用 any
是一种不好的做法,因为您会暴露自己接收和使用不正确的数据类型。
这里最简单的解决方案就是重构您的自定义 Y 轴格式化程序功能并使其与库所期望的兼容。例如,如果您 100% 确定您只会在此函数中接收数字:
const yformat = (e: number | string | Date) => {
if (typeof e === 'number') {
return Math.floor(e);
} else {
throw new Error('Unexpected value');
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。