且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

类型'string |的参数不能将'null'分配给'ValueFn< SVGPathElement,Datum [],string |编号|布尔| null>'

更新时间:2022-11-30 12:07:11

此问题与TypeScript等效,它时不时弹出各种JavaScript问题,在此情况下,开发人员会混淆在引用中传递函数与在C中调用该函数.就地传递其返回值.

This question is the TypeScript equivalent of various types of JavaScript questions that pop up every now and then where the developer confuses passing a function by reference with calling said function in situ whereby just passing its return value.

您实际上是通过执行lineGenerator(data)来调用(即执行)行生成器的.从API docs

You are actually calling, i.e. executing, the line generator by doing lineGenerator(data). As you can see from the API docs and the type definitions this will return either a string or null:

export interface Line<Datum> {
  (data: Datum[]): string | null;
  //...
}

这与

This does not match the signature of the .attr() method, though, which in this case expects a function to be passed as the second argument.

export interface Selection<GElement extends BaseType, Datum, PElement extends BaseType, PDatum> {
  //...
  attr(name: string, value: ValueFn<GElement, Datum, string | number | boolean | null>): this;
  //...
}

解决方案是将生成器传递给.attr()而不执行它:

The solution is to pass the generator to .attr() without executing it:

.attr('d', lineGenerator)

然后,生成器将通过.attr()的内部工作方式执行,并将绑定到所选内容的数据传递给该生成器.依次返回路径d属性的路径定义字符串.

The generator will then be executed by the inner workings of .attr() being passed the data bound to the selection. That, in turn, will return the path definition string for the d attribute of the path.