在TypeScript中使用D3隐藏刻度标签的报错解决方法
解决TypeScript中D3.js tickFormat隐藏刻度标签的类型错误
在JavaScript中,调用axis.tickFormat("")传入空字符串可以隐藏坐标轴的刻度标签,但在TypeScript环境下会触发如下类型错误:
TS2769: No overload matches this call. Overload 1 of 3, '(format: null): Axis<NumberValue>', gave the following error. Argument of type '"' is not assignable to parameter of type 'null'. Overload 2 of 3, '(format: (domainValue: NumberValue, index: number) => string): Axis<NumberValue>', gave the following error. Argument of type 'string' is not assignable to parameter of type '(domainValue: NumberValue, index: number) => string'. > 100 | const Xaxis = d3.axisTop(Xscale).tickFormat("");
查看D3的tickFormat类型定义可知,它只接受两种参数:
- 一个返回字符串的格式化函数
- 值为
null(表示使用刻度默认格式化器)
tickFormat(format: (domainValue: Domain, index: number) => string): this; /** * Reset the tick format function. A null format indicates that the scale’s * default formatter should be used, which is generated by calling scale.tickFormat. * In this case, the arguments specified by axis.tickArguments * are likewise passed to scale.tickFormat. * * @param format null */ tickFormat(format: null): this;
要实现隐藏刻度标签的需求,你需要传入一个始终返回空字符串的函数来替代直接传空字符串,这样既符合TypeScript的类型约束,也能达到隐藏标签的效果:
const Xaxis = d3.axisTop(Xscale).tickFormat(() => "");
内容的提问来源于stack exchange,提问作者kkinghe
相关产品推荐
相关产品推荐

