TypeScript - GeoJSON: จะหาประเภทของ Feature ได้อย่างไร?
ฉันไม่สามารถหาประเภทที่ถูกต้องสำหรับฟีเจอร์ GeoJSON โดยใช้ react-leaflet และ TypeScript ได้
ฉันสามารถนำเข้าช่องชื่อได้
import { GeoJSON [...] } from 'react-leaflet';
จัดเก็บ FeatureCollection
export type TFeatureColl = GeoJSON.FeatureCollection;
และจากนั้นเข้าไปใน Tooltip ของ VSCode สำหรับอาร์เรย์ของ features เช่น const newGeo :TFeatureColl ...; newGeo.features.map(...:
(property) FeatureCollection<Geometry, GeoJsonProperties>.features: Feature<Geometry, GeoJsonProperties>[]
แต่ฉันไม่สามารถรับประเภทของอาร์กิวเมนต์ feature ที่ถูกต้องใน 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)
};
}, []);
มีวิธีใดบ้างที่จะหาประเภทที่ถูกต้องสำหรับ คุณลักษณะเดียว?
ฉันได้ค้นหาที่เก็บของ react-leaflet, @types/react-leaflet, Google - แต่ก็ไม่พบอะไรเลย VSCode สามารถหาประเภทได้ด้วยเหตุผลบางอย่าง (อีกครั้ง โดยอิงจาก GeoJSON จาก react-leaflet) แต่ไม่ได้แสดงแหล่งที่มา
แม้ว่าฉันจะพยายามใช้ namespace ของ 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;
}), []);
ดังนั้นที่นี่ฉันจึงไม่ได้ประเภทที่ถูกต้องสำหรับ callback ของ 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) {
// ...
}
// ...
}, []);
ฉันไม่พบเอกสารใด ๆ (หรือการทดสอบ) สำหรับสิ่งนี้