I'm currently working on refining a generic function, where the autocomplete feature recognizes that it's encountering a typeguard, preventing it from revisiting the same code block. I suspect that the issue lies in not restricting the type to the Generic, but I'm not sure how to accomplish this. Is it even feasible? It seems like it should be possible, but I have doubts. Any guidance would be greatly appreciated.
// Setup
export type Feature<Geometry> = {
type: 'Feature',
geometry: Geometry
}
type Geometry = Point | Curve
interface Base {
type: string
}
interface Point extends Base{
type: 'Point'
}
interface Curve extends Base {
type: 'Curve'
}
// Typeguard
function isGeometry<G extends Geometry, U extends G['type']>(geometry: G, disciminator: U): geometry is Extract<G, {type: U}>{
return geometry.type === disciminator
}
function isFeature<G extends Geometry, U extends G['type']>(feature: Feature<G>, disciminator: U): feature is Feature<Extract<G, {type: U}>> {
return feature.geometry.type === disciminator
}
function whatGeometry(feature: Feature<Point | Curve>) {
if(isGeometry(feature.geometry, 'Curve')){
return feature.geometry;
// ^?
}
if(isGeometry(feature.geometry, 'Point')){
return feature.geometry;
// ^?
} // Autocompletes, and knows that we can't have anything else for a geometry,
return;
}
function whatFeature(feature: Feature<Point | Curve>) {
if(isFeature(feature, 'Curve')){
return feature.geometry;
// ^?
}
if(isFeature(feature, 'Point')) {
return feature;
// ^?
} // Assumes we can have another Feature<Point> even though the upper typeguard should have caught it
return;
}