首页 > 解决方案 > SVG.js:检测“元素”是否为“组”

问题描述

我需要确定通过检索的元素SVG.get()是否是组(SVG.G)。我认为这将是一个简单的instanceof检查,但我never在 Typescript 中遇到类型错误。

这是代码:

    // Get the element from the <defs> section
    const newuse = svg.get(key);
    // Set the fill colour
    const fill = "red";
    // If it's a group, go through and fill all children with the "data- playerfill" attribute
    if ( newuse instanceof svg.G ) {
        // I have to do this in Typescript because the Set doesn't have a "fill" function defined
        (newuse as svg.G).select("[data-playerfill=true]").each(function(this: svg.Element) { this.fill(fill); });
    } else {
        // Just a single element that you fill
        newuse.fill(fill);
    }                            }

问题是我在最后一行收到以下错误:

Property 'fill' does not exist on type 'never'.

据我所知,这意味着永远不会评估 else 子句。但我不确定为什么。都是SVG.Element_ SVG.G我当然不这么认为。

任何指导表示赞赏。谢谢!

标签: typescriptsvg.js

解决方案


instanceof 测试现在应该在 3.0.12 中正常工作,因为 Svg.G 现在已正确声明为一个类。


推荐阅读