I am trying to use a custom key function for .data() with .selectAll() selection in D3. But, making it TypeScript compatible is becoming such a pain.
The elements are not getting removed properly without the key function as D3 uses the index to check for updates by default.
So, here is the JavaScript code snippet, working all fine as expected:
const circles = svg
.select("g")
.selectAll("circle")
.data(data, d => d.val);
Trying the same with TypeScript,
interface IData {
val: number;
}
Attempt 1
const circles = svg
.select("g")
.selectAll("circle")
.data<IData>(data, (d) => d.val);
Object d is of type 'unknown'. TS2571
35 | .select("g")
36 | .selectAll("circle")
> 37 | .data<IData>(data, (d) => d.val);
Attempt 2
const circles = svg
.select("g")
.selectAll<SVGSVGElement, IData>("circle")
.data<IData>(data, (d) => d.val);
No overload matches this call.
Overload 1 of 3, '(data: IData[], key?: ValueFn<SVGSVGElement | Element | EnterElement | Document | Window | null, IData, string> | undefined): Selection<...>', gave the following error.
Argument of type '(this: SVGSVGElement | Element | EnterElement | Document | Window | null, d: IData) => number' is not assignable to parameter of type 'ValueFn<SVGSVGElement | Element | EnterElement | Document | Window | null, IData, string>'.
Type 'number' is not assignable to type 'string'.
Overload 2 of 3, '(data: ValueFn<BaseType, unknown, IData[]>, key?: ValueFn<SVGSVGElement | Element | EnterElement | Document | Window | null, IData, string> | undefined): Selection<...>', gave the following error.
Argument of type 'IData[]' is not assignable to parameter of type 'ValueFn<BaseType, unknown, IData[]>'.
Type 'IData[]' provides no match for the signature '(this: BaseType, datum: unknown, index: number, groups: BaseType[] | ArrayLike<BaseType>): IData[]'. TS2769
And, it is all working fine without the key function for data:
const circles = svg
.select("g")
.selectAll<SVGSVGElement, IData>("circle")
.data<IData>(data);