因此,在工作中,我们使用这些类型来创建我们的几何基础:
export type GeoJSON = Geometry | Feature;
export type GeoJsonTypes = GeoJSON['type'];
export interface GeoJsonObject { type: GeoJsonTypes; }
export interface Point extends GeoJsonObject {
type: 'Point';
coordinates: number[];
}
export interface MultiPoint extends GeoJsonObject {
type: "MultiPoint",
coordinates: number[][];
}
export type Geometry =
| Point
| MultiPoint
export interface Feature<G extends Geometry = Geometry>
extends GeoJsonObject {
type: 'Feature';
geometry: G;
}
问题是我们最终不得不为每个几何体创建单独的typeguard:
export const isPointGeometry = (g: Geometry): g is Point => {
return (g as Point).type === 'Point';
};
我试着创建一个通用的typeguard:
export function isGeometry<T extends Geometry, G extends GeoJsonObject['type']>(feature: T, geometry: G): feature is T {
return feature && feature && feature.type === geometry;
}
但是没有用。因为我仍然有问题?有人有主意吗?
export function coordinatesFor(f: Feature<Point | MultiPoint>) {
if (isGeometry(f.geometry, 'Point')) {
return f.geometry.coordinates ?? []; // Expected Feature<Point> but got Feature<Point | MultiPoint>
}
return [];
}
1条答案
按热度按时间lndjwyie1#
试试这个方法:
这里我们做两件事:
T
参数推断G
类型,以确保G
始终与给定的T
兼容,并且不可能使用错误的参数组合调用函数,例如:isGeometry(somePoint, 'Polygon')
。Extract<T, { type: G }>
,我们选择那些Geometry
联合成员,它们与(我们正在寻找的几何体){ type: G }
兼容。