代码之家  ›  专栏  ›  技术社区  ›  MKF

在OpenLayers 9.1中使用内置方法时,TypeScript和缩小并集类型

  •  1
  • MKF  · 技术社区  · 1 年前

    在尝试对以下类型使用方法时,我遇到了很多打字错误 StyleLike 在OpenLayers 9.1。在本例中,我创建了一个具有单点特征的图层,并使其使用默认样式:

    const feat = new Feature({
        geometry: new Point ([0, 0]),
        name: 'Whatever',
        population: 100,
        rain: 500
    })
    
    const vectorSource = new VectorSource({
        features: [feat]
    })
    
    const pointLayer = new VectorLayer({
        source: vectorSource
    })
    

    如果我以后想获得功能的颜色:

    const color = pointLayer.getStyle()
    console.log(color.getFill().getColor())
    

    变量 color 由typescript推断为 StyleLike | null | undefined 类型

    样式类似 定义为 Style | Style[] | StyleFunction 根据 documentation .

    这个 console.log 这条线会在下面产生一个红色的歪歪扭扭 getFill()

    Property 'getFill' does not exist on type 'StyleLike'.
      Property 'getFill' does not exist on type 'Style[]'.
    

    这是有道理的,因为是的,如果 颜色 是的 Style[] 它不会有 getFill() 方法,但在这个例子中,我知道 颜色 真的是的 Style 类型(我在调试时也确认了这一点)。这个 风格 类型具有有效的 getFill() 方法代码确实运行了,我确实得到了我想要的值,但是 如何正确定义的类型 颜色 这样我就不会出现错误了?

    决定性的 color: Style 无效。它会把一个歪歪扭扭的 颜色 然后说:

    Type 'StyleLike | null | undefined' is not assignable to type 'Style'.
      Type 'undefined' is not assignable to type 'Style'.
    
    1 回复  |  直到 1 年前
        1
  •  0
  •   jcalz    1 年前

    给定的TypeScript打字员 color 包括可能的可能性 null undefined 或者数组或函数,你应该仔细检查一下你是如何“知道”的 颜色 实际上是 Style 。调试是一个好兆头,但如果在不同的环境中运行,同一代码可能会产生不同的结果。我不确定,因为我对OpenLayers一无所知。

    无论如何,有两种通用方法,这取决于您对编写时运行时会发生什么的确定程度 color.getFill().getColor() .


    如果你真的不确定 颜色 肯定会是 风格 ,您可以编写代码来检查并说服TypeScript您所做的是类型安全的。例如

    if (color && "getFill" in color) {
        const fill = color.getFill();
        if (fill) {
            console.log(fill.getColor())
        }
    }
    

    给我们 narrow 颜色 风格 通过 truthiness checking (消除 无效的 未定义 )和 in operator narrowing (以确保 风格 而不是数组或函数)。我们还必须检查 color.getFill() 因为它也被认为是可能的 无效的 .

    这是类型安全的,但有些乏味,因为您需要不断检查内容,其中一些需要将内容复制到其他变量。(如果你所要做的就是避免 无效的 未定义 你可以使用 optional chaining 喜欢 color?.getFill()?.getColor() ,但数组/函数的事情使它不那么简单。)


    另一方面,如果你确信 颜色 不想麻烦额外的运行时检查,您可以 assert 您所知道的:

    console.log((color as Style).getFill()!.getColor())
    

    在这里 color as Style 是一个类型断言,表示您为以下事实提供担保 颜色 可以安全地被视为 风格 。我也用过 non-null assertion operator ( ! ) 关于的结果 getFill() 告诉编译器你知道它不是 无效的 。这根本不会更改运行时代码,并且可以防止编译器错误。如果你对的类型是正确的 颜色 以及它的真实性 getFill() 结果,那么这是好的。如果你错了,你会得到运行时错误。如果这种可能性不太可能让你担心,那么断言类型是完全合理的。


    是否要执行运行时检查或跳过检查取决于您的用例和需求。

    Playground link to code

    推荐文章