Description
I am using D3 library and prefer using strong type in the callback function. In case JSON parameters is changing I can refactor my code.
In the D3 one of the overload function "attr" defined as:
/**
* Sets the value of the attribute with the specified name for the selected elements and returns this selection.
* The value for the individual selected elements is determined by the value function.
*
* @param name Name of the attribute
* @param value A value function which is evaluated for each selected element, in order, being passed the current datum (d),
* the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). A null value will clear the attribute.
*/
attr(name: string, value: ValueFn<GElement, Datum, string | number | boolean | null>): this;
So, function parameter may accept:
"ValueFn<BaseType, {}, string" //is JSON Object
or "number" or "boolean" or "null"
For a JSON argument I defined a custom type
type DefaultState = {
source: {x: 10, y: 100},
target: {x: 20, y: 300}
};
Now I would like to cast this argument in my callback function. Currently my workaround using two lines.
d3.select("body").attr("path", (val:any):string => {
let d = val as DefaultState;
return "M2" + d.source.x + "," + d.source.y + "L" + d.target.x + "," + d.target.y;
})
But I would prefer using inline casting:
d3.select("body").attr("path", (d:DefaultState):string => {
return "M2" + d.source.x + "," + d.source.y + "L" + d.target.x + "," + d.target.y;
})
or
d3.select("body").attr("path", (d:any as DefaultState):string => {
return "M2" + d.source.x + "," + d.source.y + "L" + d.target.x + "," + d.target.y;
})
Unfortunately I am getting an error:
[ts]
Argument of type '(d: DefaultState) => string' is not assignable to parameter of type 'ValueFn<BaseType, {}, string | number | boolean | null>'.
Types of parameters 'd' and 'datum' are incompatible.
Type '{}' is not assignable to type 'DefaultState'.
Property 'source' is missing in type '{}'.
Can someone give me a solution. Thanks!