在 Typescript React 应用程序中导入 GeoJSON 文件时出现类型错误

问题描述 投票:0回答:1

我正在尝试使用 React-Leaflet 导入 GeoJSON 文件以在 Leaflet 地图中映射区域。我使用 create-react-app 启动了该项目。但是,当我尝试使用 GeoJSON 组件中的数据时,我收到一条错误,指示 JSON 类型不可分配给 GeoJsonObject 类型。

TS2322: Type '{ type: string; features: ({ type: string; geometry: { type: string; coordinates: number[][][][]; }; properties: { BCR: number; BCRN
AME: string; Label: string; }; } | { type: string; geometry: { type: string; coordinates: number[][][]; }; properties: { ...; }; })[]; }' is not assignable to type 'GeoJsonObject'.
...
import bar from './../../data/bar.json'

export const Page = () => {
    return(
        <main>
            <MapContainer center={[45, -95]} zoom={3}>
                <TileLayer
                    ...
                />
                <GeoJSON data={bar} />
            </MapContainer>
        </main>
    )
}

我尝试使用 npm 安装 geojson 和 @types/geojson,但这没有帮助。然而,受到这个评论的启发,我将@types/geojson的版本降级到1.0.6。这让应用程序运行,但我的 IDE 仍然抱怨类型错误:

TS2741: Property  type  is missing in type  {}  but required in type  GeoJsonObject 
index.d.ts(48, 5):  type  is declared here.
GeoJSON.d.ts(7, 5): The expected type comes from property  data  which is declared here on type
IntrinsicAttributes & GeoJSONProps & RefAttributes<GeoJSON<any, Geometry>>

有没有办法定义导入的JSON文件的类型?

reactjs typescript leaflet geojson
1个回答
0
投票

问题

TypeScript 期望 GeoJSON 数据符合 GeoJsonObject 类型,请尝试以下操作:

import React from 'react';
import { MapContainer, TileLayer, GeoJSON } from 'react-leaflet';
import { Feature, Geometry, GeoJsonObject } from 'geojson'; // Import GeoJSON types

import bar from './../../data/bar.json';

type MyGeoJsonType = GeoJsonObject & {
  features: Feature<Geometry, { BCR: number; BCRNAME: string; Label: string }>[];
};

export const Page = () => {
  const geoJsonData: MyGeoJsonType = bar;

  return (
    <main>
      <MapContainer center={[45, -95]} zoom={3}>
        <TileLayer
          // ...other props
        />
        <GeoJSON data={geoJsonData} />
      </MapContainer>
    </main>
  );
};

© www.soinside.com 2019 - 2024. All rights reserved.