javascript - 如何使用 Typescript + react-leaflet 创建 GeoJSON Feature 元素
问题描述
我正在尝试从 Typescript 中的功能创建一个 <GeoJSON {...} /> 反应元素,但没有成功。(我正在使用 react-leaflet + Typescript)使用常规 js,我只需要执行以下操作:
<Map
{...}
<GeoJSON
data={...} <- Here I put my feature in JSON format
style={...} <- Associated style
/>
/>
但是在 Typescript 中,如果我尝试做完全相同的事情,我会遇到以下错误:
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 类型定义时,几何不存在,只有“类型”字段,那么我应该如何将几何传递给我试图创建的 GeoJSON 元素?(GeoJsonObject 的类型定义:http: //definitelytyped.org/docs/geojson--geojson/interfaces/geojson.geojsonobject.html)
如果我在“常规”javascript 中尝试这段代码,它确实有效,你知道为什么吗?
解决方案
解决方案 1(推荐)
为您感兴趣的 GeoJson 对象使用正确的类型。
import { GeoJSON } from 'react-leaflet';
const data: GeoJSON.Feature = {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [125.6, 10.1],
},
properties: {},
};
<Map
{...}
<GeoJSON data={data} />
/>
解决方案 2(不推荐)
告诉 Typescript 编译器它应该将对象视为 type GeoJsonObject
。
import { GeoJsonObject } from 'geojson';
<Map
{...}
<GeoJSON
data={{
type: "Feature",
geometry: {
type: "Point",
coordinates: [125.6, 10.1]
}
} as GeoJsonObject }
/>
/>
推荐阅读
- c# - 在 ASP.NET MVC 中的上传文件中使用 TempData
- r - 将来不会使用嵌套计划(多会话)释放内存
- r - 如何保存我训练有素的随机森林模型并将其一一应用于测试数据文件?
- python - Tkinter 实时动画
- python - 将列分配给层次更高的多索引级别
- javascript - 如何在 JavaScript 中将字符串参数转换为 Object 类型?
- python - 如何在 jupyter notebook 的代码中删除几个空行?
- android - 使用作业服务获取当前 SSID
- python - 如何从列中删除非数字字符
- jenkins - Jenkins 文件在参数类型之间进行选择