javascript - 如何使用 Typescript + react-leaflet 创建 GeoJSON Feature 元素

标签 javascript typescript leaflet react-leaflet

我正在尝试从 Typescript 中的功能创建一个 react 元素,但没有成功。 (我正在使用 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 编译器它应该将对象视为类型 GeoJsonObject .
import { GeoJsonObject } from 'geojson';

<Map
    {...}
    <GeoJSON
        data={{
            type: "Feature",
            geometry: {
                type: "Point",
                coordinates: [125.6, 10.1]
            }
        } as GeoJsonObject }
    />
/>

关于javascript - 如何使用 Typescript + react-leaflet 创建 GeoJSON Feature 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60349547/

相关文章:

angularjs - Restangular错误拦截器-如何将自定义对象传递给不了解restangular的 Controller ?

json - 无法将事件/弹出窗口绑定(bind)到现有传单 geojson 层

javascript - 如何使用 this 关键字从方法访问类属性

javascript - 在传单绘制的编辑控件中分配多个功能组

javascript - 在 Javascript 中使用新函数扩展对象

javascript - 如何迭代 JSON 对象?

javascript - 从 D3 中的多个 csv 文件导入数据

javascript - FireFox 上的 contentEditable div 多行问题

reactjs - TS2531 : Object possibly 'null'

Angular 6 应用程序找不到命名空间 'google'