我有一种可以从对象的一个字段中扣除的类型。
我编写了这个函数,它接受 zoneType 并返回关联区域。
但最后,每次通话时我都会得到: MyType1 |我的类型2 | MyType3
而不是关联的类型。该类型实际上可以从参数中扣除,因为 switch case 可以轻松找到该类型。
顺便说一句,我们正在谈论 geojson。
我想尝试重载,但 typescript 不允许有重复的函数。 另外,推断一下,但是对于 TS 本身可以猜测的东西来说,它看起来“巨大”?
我将感谢您的帮助。
谢谢!
type MyType1 = "geojson.Feature<geojson.MultiPolygon>";
type MyType2 = "geojson.Feature<geojson.Polygon>";
type MyType3 = "geojson.FeatureCollection<geojson.Polygon>";
export type ZoneGeojson = MyType1 | MyType2 | MyType3;
type InternalZone = {
id: number;
zone: ZoneGeojson | null;
zone_type: ZoneZoneType;
};
export interface Zone1 extends InternalZone {
zone_type: ZoneZoneType.Type1 | ZoneZoneType.Type2;
zone: MyType1 | null;
}
export interface Zone2 extends InternalZone {
zone_type: ZoneZoneType.Type3;
zone: MyType1 | null;
}
export interface Zone3 extends InternalZone {
zone_type: ZoneZoneType.Type4;
zone: MyType1 | null;
}
export const exportZone = (
zoneType: ZoneZoneType,
zone: FeatureCollection<Polygon>,
) => {
switch (zoneType) {
case ZoneZoneType.Type1:
case ZoneZoneType.Type2:
return zone1.zoneGeojsonFactory.exportZoneEdition(zone);
case ZoneZoneType.Type3:
return zone2.zoneGeojsonFactory.exportZoneEdition(zone);
case ZoneZoneType.Type4:
return zone3.zoneGeojsonFactory.exportZoneEdition(zone);
default:
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw new Error(`Unknown zone type ${zoneType ?? '[undefined]'}`);
}
};
最佳答案
这是 return type based on parameter 的一些具体情况
适用于您的案例:
type ObjectType<T> =
T extends ZoneZoneType.Type1 ? Zone1 :
T extends ZoneZoneType.Type2 ? Zone1 :
T extends ZoneZoneType.Type3 ? Zone2 :
T extends ZoneZoneType.Type4 ? Zone3 :
never;
export const exportZoneEditionGeojson = <T extends ZoneZoneType>(
zoneType: T,
zoneEditionGeojson: FeatureCollection<Polygon>,
): ObjectType<T> => {
switch (zoneType) {
case ZoneZoneType.Type1:
case ZoneZoneType.Type2:
return zone1.zoneGeojsonFactory
.exportZoneEdition(zoneEditionGeojson) as ObjectType<T>;
case ZoneZoneType.Type3:
return zone2.zoneGeojsonFactory
.exportZoneEdition(zoneEditionGeojson) as ObjectType<T>;
case ZoneZoneType.Type4:
return zone3.zoneGeojsonFactory
.exportZoneEdition(zoneEditionGeojson) as ObjectType<T>;
default:
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
throw new Error(`Unknown zone type ${zoneType}`);
}
};
关于typescript - 如何从 typescript 中的参数推断或推导返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76375869/