Issue
I am trying to get the union type of generics in an array but can only retrieve what the generic is extended from not the actual implementation.
type Params = Record<string, number | string | null | undefined> | undefined;
type Route<T extends Params = undefined> = {
params: T
}
type Stack = {
routes: Route<Params>[];
}
const route1: Route<{ detailUrl: string }> = { ... };
const route2: Route<{ head: string }> = { ... };
const route3: Route = { ... };
const routeRegistry: Stack = {
routes: [route1, route2, route3]
};
type UnionOfParams = ExtractGeneric<typeof routeRegistry['routes'][number]>;
// expected: { detailUrl: string } | { head: string } | undefined
// received: Params
I know const assertion is useful to limit widening of the inference of the types, but using it in this case didn't produce any result.
I couldn't find anything related to this particular problem. Is there a way to accomplish what I ask?
Solution
You can't have inference and an annotation for a variable. This can only be done with a function. A function can have a generic type parameter that both constrains a parameter and offers a vehicle for inference:
function createRouteRegistry<T extends Stack>(p: T): T {
return p
}
const routeRegistry = createRouteRegistry({
routes: [route1, route2, route3]
})
type ExtractGeneric<T> = T extends Route<infer P> ? P : never
type UnionOfParams = ExtractGeneric<typeof routeRegistry['routes'][number]>;
Answered By - Titian Cernicova-Dragomir
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.