首页 > 解决方案 > 如何使用 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 中尝试这段代码,它确实有效,你知道为什么吗?

标签: javascripttypescriptleafletreact-leaflet

解决方案


解决方案 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 }
    />
/>

推荐阅读