我正在处理一个具有嵌套路由的路由库,我试图在其中定义子处理程序函数来推断父路径.原因是我有另一种类型,可以从字符串(例如,users/:id
到{ id: string }
)推断动态路径参数;因此,我希望能够将推断的路径参数从父路由传递到每个子路由处理程序函数中的任何和所有子路由.
以下是我目前掌握的情况:
type RawRouterDefn<Namespace extends string = ""> = {
[K: string]: Handler<Namespace, typeof K> | RawRouterDefn<`${Namespace}/${typeof K}`>;
};
type Handler<DataPath extends string, Path extends string> = ((args: { dataPath: DataPath, path: Path }) => unknown)
type Router<Routes extends RawRouterDefn, DataPath extends string = ""> = {
[K in keyof Routes & string]: Routes[K] extends CallableFunction
? Handler<DataPath, K>
: Router<Routes[K], `${DataPath}/${K}`>;
};
function createRouter<T extends RawRouterDefn>(rawDefn: T): Router<T, ""> {
// Implementation not important right now
return {} as unknown as Router<T, "">
}
const router = createRouter({
some: {
deeply: {
nested: {
/**
* Here, dataPath should be inferred as `some/deeply/nested`,
* path should be `route`
*/
route: ({ dataPath, path }) => {}
},
},
},
});
const route = router.some.deeply.nested.route;
// Correctly inferred **after** function applied, I need it within the router definition
type Params = Parameters<typeof route>[0]
(link美元到操场)
我就快到了,除了dataPath
应该被推断为/some/deeply/nested
而不是/${string}/${string}/${string}
,path
应该被推断为/route
而不是/${string}
.这在我看来,我在RawRouterDefn
机型中遗漏了一些东西.
因此,我似乎可以正确地缩小弦的形状,但不能用我目前的方法进一步缩小.
同样,我需要在将其用作函数参数时进行推断,而不是在之后.