我试图在数组中获取泛型的联合类型,但只能检索泛型从实际实现中扩展的内容。
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
我知道 const 断言对于限制类型推断的扩大很有用,但在这种情况下使用它不会产生任何结果。
我找不到与此特定问题相关的任何信息。有什么办法可以完成我的要求吗?
最佳答案
您不能对变量进行推理和注释。这只能通过一个函数来完成。一个函数可以有一个泛型类型参数,它既约束参数又提供推理工具:
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]>;
Playground Link
https://stackoverflow.com/questions/70434911/