[您很可能只是错过了GeoJSON要素对象的properties
成员(可能是一个空对象):http://definitelytyped.org/docs/geojson--geojson/interfaces/geojson.feature.html
我正在尝试从Typescript中的Feature创建一个react元素,但没有成功。 (我正在使用react-leaflet + Typescript)使用普通的js,我只需要做类似的事情:
<Map
{...}
<GeoJSON
data={...} <- Here I put my feature in JSON format
style={...} <- Associated style
/>
/>
但是在打字稿中,如果我尝试做完全相同的事情,则会遇到以下错误:
No overload matches this call.
Overload 1 of 2, '(props: Readonly<GeoJSONProps>): GeoJSON<GeoJSONProps, GeoJSON<any>>', gave the following error.
Type '{ type: string; geometry: { type: string; coordinates: number[]; }; }' is not assignable to type 'GeoJsonObject'.
Object literal may only specify known properties, and 'geometry' does not exist in type 'GeoJsonObject'.
Overload 2 of 2, '(props: GeoJSONProps, context?: any): GeoJSON<GeoJSONProps, GeoJSON<any>>', gave the following error.
Type '{ type: string; geometry: { type: string; coordinates: number[]; }; }' is not assignable to type 'GeoJsonObject'.
Object literal may only specify known properties, and 'geometry' does not exist in type 'GeoJsonObject'.ts(2769)
这里是我尝试过的许多事情的样本:
<Map
{...}
<GeoJSON
data={{
type: "Feature",
geometry: {
type: "Point",
coordinates: [125.6, 10.1]
}
}}
/>
/>
[当我检查GeoJsonObject类型定义时,不存在几何图形,只有“ type”字段,所以我应该如何将几何图形传递给我要创建的GeoJSON元素? (GeoJsonObject的类型定义:http://definitelytyped.org/docs/geojson--geojson/interfaces/geojson.geojsonobject.html)
如果我在“常规” javascript中尝试此代码,它确实可以工作,你知道为什么吗?
感谢您的帮助!
我认为错误在于GeoJSON组件的代码和类型。看起来该组件期望GeoJsonObject
,但不接受Feature
。您可以尝试将data
属性的类型更改为Feature<Point>
,然后检查该错误是否消失。
这里发生了几件事。
首先,根据@types/geojson
类型定义,点要素需要将type
字段设置为“特征”的string literal type(并且几何对象定义为具有type
字段,且“ Point”的字符串文字类型)。
其次,TypeScript编译器无法推断出“类型”字段具有正确的字符串文字类型(它推断出它们是更普通的类型“字符串”)。可以在this answer中找到关于“类型脚本-为什么不能推断出此字符串文字类型?”的很好解释。
现在我们了解了问题,我们可以解决它。这是您的示例,应该以一种可行的方式进行修改:
<Map {...} <GeoJSON data={{ type: "Feature" as "Feature", geometry: { type: "Point" as "Point", coordinates: [125.6, 10.1] } }} /> />
唯一的区别是两个type assertions
as "Feature"
和as "Point"
相加,它们告诉TypeScript编译器这些“ type:”字段分别具有字符串特征类型“ Feature”和“ Point”。
为了减少重复,您也可以使用as const
代替as "Feature"
等。>
[您很可能只是错过了GeoJSON要素对象的properties
成员(可能是一个空对象):http://definitelytyped.org/docs/geojson--geojson/interfaces/geojson.feature.html
{
type: "Feature",
geometry: {
type: "Point",
coordinates: [125.6, 10.1]
},
properties: {} // Not optional for a Feature
}
[您很可能只是错过了GeoJSON要素对象的properties
成员(可能是一个空对象):http://definitelytyped.org/docs/geojson--geojson/interfaces/geojson.feature.html