当我try 在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
})
如果我以后想获取特征的 colored颜色 :
const color = pointLayer.getStyle()
console.log(color.getFill().getColor())
类型脚本推断变量color
为StyleLike | null | undefined
类型.
根据documentation将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()
方法.代码确实运行并且我确实得到了我想要的值,但how do I properly define the type of 100 so I don't get error squigglies?
定义color: Style
无效.它会在color
下面放一个曲线,并说:
Type 'StyleLike | null | undefined' is not assignable to type 'Style'.
Type 'undefined' is not assignable to type 'Style'.