I'm trying to create a <GeoJSON {...} \/> react element from a Feature in Typescript, without success. (I'm using react-leaflet + Typescript) With regular js, I just have to do something like that:
<Map
{...}
<GeoJSON
data={...} <- Here I put my feature in JSON format
style={...} <- Associated style
/>
/>
I think the error is on the code and typing of the GeoJSON component. It looks as if that component expects a GeoJsonObject
and does not accept the Feature
. You could try changing the type of the data
property to Feature<Point>
and check if that error goes away.
There are a couple of things happening here.
First, according to the @types/geojson
type definitions, a point Feature needs to have a type
field set to a string literal type of "Feature" (and the geometry object is defined to have a type
field with a string literal type of "Point").
Second, the TypeScript compiler isn't able to infer that the "type" fields have the correct string literal type (it infers they are instead of the more general type "string"). A good explanation for this sort of thing can be found in this answer to the question "Typescript - Why can't this string literal type be inferred?".
Now that we understand the problem, we can fix it. Here's your example modified in a way that should work:
<Map
{...}
<GeoJSON
data={{
type: "Feature" as "Feature",
geometry: {
type: "Point" as "Point",
coordinates: [125.6, 10.1]
}
}}
/>
/>
The only difference is the addition of the two type assertions as "Feature"
and as "Point"
which tell the TypeScript compiler these "type:" fields have the string literal types of "Feature" and "Point", respectively.
To reduce duplication, you can also use as const
instead of as "Feature"
etc.
Very probably you just miss the properties
member (possibly an empty object) of your GeoJSON Feature object(s): http://definitelytyped.org/docs/geojson--geojson/interfaces/geojson.feature.html
{
type: "Feature",
geometry: {
type: "Point",
coordinates: [125.6, 10.1]
},
properties: {} // Not optional for a Feature
}
Use the correct type for the GeoJson object you are interested in.
<\/h1>
Tell the Typescript compiler that it should treat the object as of type
GeoJsonObject<\/code> .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.