typescript 通用类型保护

zi8p0yeb  于 2023-06-07  发布在  TypeScript
关注(0)|答案(1)|浏览(223)

因此,在工作中,我们使用这些类型来创建我们的几何基础:

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 [];
 }
lndjwyie

lndjwyie1#

试试这个方法:

function isGeometry<T extends Geometry, G extends T['type'] = Geometry['type']>(
  feature: T,
  geometry: G,
): feature is Extract<T, { type: G }> {
  return feature && feature && feature.type === geometry;
}

这里我们做两件事:

  • 我们根据T参数推断G类型,以确保G始终与给定的T兼容,并且不可能使用错误的参数组合调用函数,例如:isGeometry(somePoint, 'Polygon')
  • 返回类型为Extract<T, { type: G }>,我们选择那些Geometry联合成员,它们与(我们正在寻找的几何体){ type: G }兼容。

相关问题