在 OpenLayers 9.1 中使用内置方法时的 TypeScript 和缩小联合类型

问题描述 投票:0回答:1

尝试在 OpenLayers 9.1 中的

StyleLike
等类型上使用方法时,遇到很多打字稿错误。在此示例中,我创建一个具有单点特征的图层并让它使用默认样式:

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
被打字稿推断为
StyleLike | null | undefined
类型。

根据

文档

StyleLike
被定义为 Style | Style[] | StyleFunction

console.log
线将在
getFill()
下产生红色波浪线,表示:

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

这是有道理的,因为是的,如果

color
Style[]
它不会有
getFill()
方法,但在这个例子中,我知道
color
确实是
Style
类型(我也证实了这一点)调试)。
Style
类型有一个有效的
getFill()
方法。代码确实运行了,我确实得到了我想要的值,但是如何正确定义
color
的类型,这样我就不会收到错误波浪线?

定义

color: Style
无效。它会在
color
下面画一条曲线并说:

Type 'StyleLike | null | undefined' is not assignable to type 'Style'.
  Type 'undefined' is not assignable to type 'Style'.
typescript openlayers
1个回答
0
投票

鉴于

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

无论如何,有两种通用方法,具体取决于您对编写时知道运行时会发生什么的确定程度。


如果您不确定
color.getFill().getColor()

一定是

color
,您可以编写代码来检查并说服 TypeScript 您正在做的事情是类型安全的。例如:
Style

在这里,我们通过
真实性检查

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

color
)和
Style运算符缩小(以确保它是
null
而不是数组或功能)。我们还必须检查
undefined
的真实性,因为据说它也可能 in
这是类型安全的,但有些乏味,因为您需要不断检查事物,其中一些需要将事物复制到其他变量。 (如果您所要做的就是避免
Style
color.getFill()
,您可以使用像
null
一样的

可选链

,但数组/函数的事情阻止它变得那么简单。)


另一方面,如果您确定
null并且不想进行额外的运行时检查,您可以只断言
您所知道的:

undefined

这里

color?.getFill()?.getColor()
是一个类型断言,表示您保证 color 可以安全地被视为

console.log((color as Style).getFill()!.getColor())
。我还在 
color as Style

的结果上使用了

非空断言运算符 (
color
)
告诉编译器您知道它不是
Style
。这根本不会改变运行时代码,并且可以防止编译器错误。如果您对 !
 的类型及其 
getFill()
结果的真实性的判断是正确的,那么这就很好。如果你错了,你会得到运行时错误。如果这种可能性不太可能让您担心,那么断言类型是完全合理的。

您是否想要进行运行时检查或跳过它们取决于您的用例和要求。
Playground 代码链接

    


© www.soinside.com 2019 - 2024. All rights reserved.