I am trying to import a GeoJSON file to map region in a Leaflet map using React-Leaflet. I started the project using create-react-app. However, when I try to use the data in the GeoJSON component, I receive an error indicating the JSON type is not assignable to type 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>
)
}
I have tried installing geojson and @types/geojson using npm, but that didn’t help. However, inspired by this comment, I downgraded the version of @types/geojson to 1.0.6. This let the app run, but my IDE is still complaining about a type error:
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>>
Is there a way to define the type of the imported JSON file?
2
Answers
I managed to solve my problem by casting the GeoJSON object within the component.
Issue
TypeScript expects the GeoJSON data to conform to the GeoJsonObject type.
Solution
includes specific properties expected in your GeoJSON data.
Make sure to adjust the type definition based on the structure of your actual GeoJSON data. This should help TypeScript recognize the GeoJSON type correctly and resolve the issue you’re facing.
Note to Isaa:
I see you’re a new contributor, welcome! Make sure to check out this page on what to do with answers to your questions!
https://stackoverflow.com/help/someone-answers