首页 > 解决方案 > 如何使用打字稿在 d3 svg 上正确键入缩放?

问题描述

我有这个代码:

if (svg) {
    // zoom
    // svg type = d3.Selection<SVGSVGElement, unknown, null, undefined>
    const zoomBehavior = d3
      .zoom()
      .scaleExtent([0.5, 5])
      .translateExtent([
        [0, 0],
        [containerWidth, containerHeight],
      ])
      .on("zoom", (event) => {
        const zoomState = event.transform;
        console.log("zoomState", zoomState);
      });
    svg.call(zoomBehavior);
  }

我收到此错误类型:

Argument of type 'ZoomBehavior<Element, unknown>' is not assignable to parameter of type '(selection: Selection<SVGSVGElement, unknown, null, undefined>, ...args: any[]) => void'.

我不想使用 ts-ignore

标签: typescriptd3.js

解决方案


您可以在函数的泛型中定义缩放行为的类型,以匹配调用它的 SVG 选择的类型。

由于您的 SVG 选择键入为d3.Selection<SVGSVGElement, unknown, null, undefined>,因此:

   const zoomBehavior = d3
      .zoom<SVGSVGElement, unknown>()
   ...

推荐阅读