如何在TypeScript中创建包含Blob类型属性的接口?
解决方案
首先明确:如果数据库返回的geometry确实是Blob类型(比如二进制地理数据、序列化的空间对象),直接把any换成Blob完全可行,这比用any类型安全得多,TypeScript能帮你做类型校验。
如果geometry其实是GeoJSON格式的几何结构(毕竟你的结构里有type: "Feature",这是GeoJSON的典型特征),那用Blob就不合适了,这时候需要定义对应的几何类型,而不是用any。
情况1:geometry是Blob类型
直接修改接口,把any替换成Blob:
interface Feature { type: "Feature"; geometry: Blob; featureId: string; } interface QueryResult { featureStyleName: string; featureType: string; features: Feature[]; }
情况2:geometry是GeoJSON几何类型
这是更常见的场景,你可以手动定义GeoJSON的几何类型,覆盖常用的空间结构:
// 定义GeoJSON坐标类型 type GeoJsonCoordinate = [number, number] | [number, number, number]; // 定义所有可能的几何类型 type GeoJsonGeometry = | { type: "Point"; coordinates: GeoJsonCoordinate } | { type: "LineString"; coordinates: GeoJsonCoordinate[] } | { type: "Polygon"; coordinates: GeoJsonCoordinate[][] } | { type: "MultiPoint"; coordinates: GeoJsonCoordinate[] } | { type: "MultiLineString"; coordinates: GeoJsonCoordinate[][] } | { type: "MultiPolygon"; coordinates: GeoJsonCoordinate[][][] }; interface Feature { type: "Feature"; geometry: GeoJsonGeometry; featureId: string; } interface QueryResult { featureStyleName: string; featureType: string; features: Feature[]; }
这样TypeScript就能识别geometry的具体结构,避免any带来的类型不安全问题。如果需要更完整的GeoJSON类型支持,也可以安装@types/geojson包,直接使用里面的Geometry类型。
内容的提问来源于stack exchange,提问作者Karim Fayed
相关产品推荐
相关产品推荐

