Splitting up the route function #26
-
I am trying to make a component that prepends a specific route path and passes the rest of the props to the route function. However, I'm finding it hard to get typescript happy. E.g. type AdminRouteProps = {
to: ???
params: ???
};
function adminRoute<???>({ to, params }: AdminRouteProps) {
let userId = useUserId();
// E.g. There is also a '/admin/:userId/:otherParam'
return route(`/admin/:userId${to}`, {userId, ...params});
}
type AdminBreadcrumbProps = ...
function AdminBreadcrumb({ to, params }: AdminBreadcrumbProps) {
return <Link to={adminRoute({ to, params })} />;
} What's the way to get this functionally working? Thanks 😄 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Any help on this? |
Beta Was this translation helpful? Give feedback.
-
Hey @moishinetzer, sorry for late response! For some reason, Github doesn't notify me about new discussions. Considering the following generated routes example: declare module "routes-gen" {
export type RouteParams = {
"/admin/:userId": { userId: string };
"/admin/:userId/invoices": { userId: string };
"/admin/:userId/invoices/:invoiceId": { userId: string; invoiceId: string };
};
export function route<
T extends
| ["/admin/:userId", RouteParams["/admin/:userId"]]
| ["/admin/:userId/invoices", RouteParams["/admin/:userId/invoices"]]
| ["/admin/:userId/invoices/:invoiceId", RouteParams["/admin/:userId/invoices/:invoiceId"]]
>(...args: T): typeof args[0];
} Here's how you could potentially achieve your goal: import { route } from "routes-gen";
import type { RouteParams } from "routes-gen";
type RoutesStartingWith<Needle extends string> =
keyof RouteParams extends `${Needle}${infer Rest}`
? Exclude<Rest, "">
: never;
function useAdminRoute() {
const userId = useUserId();
return <AdminRoute extends RoutesStartingWith<"/admin/:userId">>({
to,
params,
}: {
to: AdminRoute;
params: Omit<RouteParams[`/admin/:userId${AdminRoute}`], "userId">;
}) => {
const fullPath = `/admin/:userId${to}` as const;
return route(fullPath, { userId, ...params } as any);
};
}
// In your component:
const adminRoute = useAdminRoute();
adminRoute({ to: "/invoices/:invoiceId", params: { invoiceId: "123" } }); Note that I've implemented a Let me know if it works. |
Beta Was this translation helpful? Give feedback.
Hey @moishinetzer, sorry for late response! For some reason, Github doesn't notify me about new discussions.
Considering the following generated routes example: