如何区分具有泛型的联合?
我正在努力根据它们的几何形状(在显示一些 GeoJSON 数据的上下文中)自动推断不同类型项目的类型。
我使用的是通用类型,因此我没有设法设置自定义类型保护,因为它可以让我区分“个人”项目和“聚合”,但不能区分不同类型的“个人”项目。
基本上,我需要推理级别:
- 区分单个项目和聚合
- 区分每个类别中的不同几何形状。
我创建了一个简化示例,在我的真实应用程序中,我有 4 种不同类型的项目,它们可能具有不同的几何形状。
这是一个 TypeScript playground,代码如下:
type A = {type: "A", a: string}
type B = {type: "B", b: string}
type C = {type: "C", c: string}
type Geometries = A | B | C
type IndividualFeature<G extends A | B = A | B> = { geometry: G, indivAttribute: string}
type AggregateFeature = { geometry: C, aggAttribute: string}
type DisplayableFeature = IndividualFeature | AggregateFeature
const display = (feature: DisplayableFeature) => {
switch(feature.geometry.type) {
case "A":
console.log("type A", feature.geometry.a, feature.indivAttribute);
return;
case "B":
console.log("type B", feature.geometry.b, feature.indivAttribute)
return;
case "C":
console.log("type C", feature.geometry.c, feature.aggAttribute)
default:
// should not happen
}
}
const indivFeature: IndividualFeature = { geometry: { type: "A", a: "a"}, indivAttribute: "hello indiv"}
const aggFeature: AggregateFeature = { geometry: { type: "C", c: "c"}, aggAttribute: "hello agg"}
几何图形被正确区分,但不是单独与聚合(feature.indivAttribute/feature.aggAttribute触发错误)。为了记录,我已经尝试了一个类型保护:这允许我区分“Indiv”和“Aggregates”,但我已经失去了几何的辨别力。
我应该如何构建我的类型/代码,以便feature.indivAttribute在此示例中正确识别为有效属性?