I cannot find the right type for GeoJSON features by using react-leaflet and TypeScript.
I can import the namespace
import { GeoJSON [...] } from 'react-leaflet';
store the FeatureCollection
export type TFeatureColl = GeoJSON.FeatureCollection;
and then get in a Tooltip of VSCode for an array of features like const newGeo :TFeatureColl ...; newGeo.features.map(...:
(property) FeatureCollection<Geometry, GeoJsonProperties>.features: Feature<Geometry, GeoJsonProperties>[]
But I cannot get the right type of the argument feature in my style callback
<GeoJSON key={new Date().toISOString()} data={data as TFeatureColl} onEachFeature={handleFeature} style={styleFeature}/>
const styleFeature = useCallback((feat /* cannot be found: Feature<Geometry, GeoJsonProperties>*/) :PathOptions => {
// shows 'any' for 'properties'
const props = feat.properties;
if (!props) {
return /* some stuff */;
}
// problem here: 'osm_id' is missing in props validation
const osmId = props.osm_id;
return {
// would be defined by some data
fillColor: '#0a0',
color: '#f0' + Math.floor(Math.random() * 10)
};
}, []);
Is there any way to find the right type for a single feature?
I have searched the repository of react-leaflet, @types/react-leaflet, Google - nothing came up. VSCode can find the type somehow (again, based on GeoJSON from react-leaflet), but do not offer the source.
Even if I try to use the GeoJSON namespace for typing it fails:
/*
TS2322: Type '(feature: GeoJSON.Feature<GeoJSON.Geometry, GeoJSON.GeoJsonProperties>) => PathOptions' is not assignable to type 'PathOptions | StyleFunction<any> | undefined'.
Type '(feature: GeoJSON.Feature<GeoJSON.Geometry, GeoJSON.GeoJsonProperties>) => PathOptions' is not assignable to type 'StyleFunction<any>'.
Types of parameters 'feature' and 'feature' are incompatible.
Type 'Feature<Geometry, any> | undefined' is not assignable to type 'Feature<Geometry, GeoJsonProperties>'.
Type 'undefined' is not assignable to type 'Feature<Geometry, GeoJsonProperties>'.
*/
const styleFeature = useCallback((feature: GeoJSON.Feature<GeoJSON.Geometry, GeoJSON.GeoJsonProperties>) :PathOptions => {
const osmId = props.osm_id;
}), []);
So here I do not get the right type for the callback of style={func} - and I am lost.
Edit
Solution for now:
const styleFeature = useCallback((feature: GeoJSON.Feature<GeoJSON.Geometry, any> | undefined) :PathOptions => {
const props = feature && feature.properties;
const properties = props as GeoJSON.GeoJsonProperties;
if (!properties) {
// ...
}
// ...
}, []);