T
TanStack2y ago
flat-fuchsia

Make a type safe URL string with params and searchParams so that users can copy i

Given a route, is there a way to create a strongly typed url string for users to copy?
const rootRoute = new RootRoute();
const publicUrl = new Route({
getParentRoute: () => rootRoute,
path: "/public/$id",
...
});

// Anything like this?
publicUrl.toString({ id: "f5ed9f10-345e-4164-9a8d-8f53a94de5d1" });
// outputs `/public/f5ed9f10-345e-4164-9a8d-8f53a94de5d1`
const rootRoute = new RootRoute();
const publicUrl = new Route({
getParentRoute: () => rootRoute,
path: "/public/$id",
...
});

// Anything like this?
publicUrl.toString({ id: "f5ed9f10-345e-4164-9a8d-8f53a94de5d1" });
// outputs `/public/f5ed9f10-345e-4164-9a8d-8f53a94de5d1`
3 Replies
like-gold
like-gold2y ago
I did something like this
// This is a util function for creating typed objects that can be passed to navigate() functions and <Link> components
export function createNavigationOptions<
TRouteTree extends AnyRoute = RegisteredRouter['routeTree'],
TFrom extends RoutePaths<TRouteTree> | string = string,
TTo extends string = '',
TMaskFrom extends RoutePaths<TRouteTree> | string = TFrom,
TMaskTo extends string = '',
>(options: NavigateOptions<TRouteTree, TFrom, TTo, TMaskFrom, TMaskTo>) {
return options
}


const options = createNavigationOptions({
to: '/$account/$project',
params: { account, project },
})

const pathname = router.buildLocation(options).pathname
// This is a util function for creating typed objects that can be passed to navigate() functions and <Link> components
export function createNavigationOptions<
TRouteTree extends AnyRoute = RegisteredRouter['routeTree'],
TFrom extends RoutePaths<TRouteTree> | string = string,
TTo extends string = '',
TMaskFrom extends RoutePaths<TRouteTree> | string = TFrom,
TMaskTo extends string = '',
>(options: NavigateOptions<TRouteTree, TFrom, TTo, TMaskFrom, TMaskTo>) {
return options
}


const options = createNavigationOptions({
to: '/$account/$project',
params: { account, project },
})

const pathname = router.buildLocation(options).pathname
You could just put the option right into router.buildLocation as well, but it doesn't seem to type the params correctly
flat-fuchsia
flat-fuchsiaOP2y ago
thanks, I'll give it a try Worked perfectly, I put the options in directly and had some issues with search params but not a problem at all.
like-gold
like-gold2y ago
Glad to hear!

Did you find this page helpful?