TypeScript - GeoJSON: Featureの型を取得するには?
私は react-leaflet と TypeScript を使って GeoJSON のフィーチャーに適したタイプを見つけることができません。
名前空間をインポートできます
import { GeoJSON [...] } from 'react-leaflet';
FeatureCollection を保存する
export type TFeatureColl = GeoJSON.FeatureCollection;
そして、次のような配列の features に対して VSCode のツールチップに入ります: const newGeo :TFeatureColl ...; newGeo.features.map(...:
(property) FeatureCollection<Geometry, GeoJsonProperties>.features: Feature<Geometry, GeoJsonProperties>[]
しかし、style コールバックで引数 feature の正しい型を取得できません
<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)
};
}, []);
単一の特徴に対して正しいタイプを見つける方法はありますか?
私は react-leaflet、@types/react-leaflet のリポジトリや Google を検索しましたが、何も見つかりませんでした。VSCode は何とか型を見つけることができます(再び react-leaflet の GeoJSON に基づいています)が、ソースは提供しません。
GeoJSON 名前空間を型指定に使おうとしても、失敗します:
/*
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;
}), []);
ここでは、style={func} のコールバックの正しい型がわからず、途方に暮れています。
編集
とりあえずの解決策:
const styleFeature = useCallback((feature: GeoJSON.Feature<GeoJSON.Geometry, any> | undefined) :PathOptions => {
const props = feature && feature.properties;
const properties = props as GeoJSON.GeoJsonProperties;
if (!properties) {
// ...
}
// ...
}, []);
これについてのドキュメント(またはテスト)は見つかりませんでした。