T
TanStack2y ago
adverse-sapphire

What should be the type of prop that needs to be passed to "to" option of redirect function

Similar question: https://discord.com/channels/719702312431386674/1210385988732325888 I have a component that accepts a redirectTo props. I use this redirectTo prop to pass to redirect function. ex:
import { redirect } from '@tanstack/react-router'

type ComponentProps = {redirectTo: string}

export default function MyComponent({redirectTo}: ComponentProps) {

return <button onClick={() => redirect({to: redirectTo})}>Redirect</button>
}
import { redirect } from '@tanstack/react-router'

type ComponentProps = {redirectTo: string}

export default function MyComponent({redirectTo}: ComponentProps) {

return <button onClick={() => redirect({to: redirectTo})}>Redirect</button>
}
Although {redirectTo: string} works but I want the typing to be more strict. What should be the type ? I tried
type ComponentProps = {
redirectTo?: Parameters<typeof redirect>[0]["to"];
}
type ComponentProps = {
redirectTo?: Parameters<typeof redirect>[0]["to"];
}
But I'm unable to get the autocomplete working for redirectTo prop
2 Replies
vicious-gold
vicious-gold2y ago
If you just want auto-complete for the all the possible to paths, then you could do this.
import { RegisteredRouter, AnyRoute, ToPathOption, RoutePaths } from '@tanstack/react-router';

type ComponentProps<
TRouteTree extends AnyRoute = RegisteredRouter['routeTree'],
TFrom extends RoutePaths<TRouteTree> | string = string,
TTo extends string = "",
> = {
redirectTo?: ToPathOption<TRouteTree, TFrom, TTo>
}
import { RegisteredRouter, AnyRoute, ToPathOption, RoutePaths } from '@tanstack/react-router';

type ComponentProps<
TRouteTree extends AnyRoute = RegisteredRouter['routeTree'],
TFrom extends RoutePaths<TRouteTree> | string = string,
TTo extends string = "",
> = {
redirectTo?: ToPathOption<TRouteTree, TFrom, TTo>
}
But this ideally wouldn't really trigger a redirection since the redirect helper is only meant to be used in the beforeLoad and loader callbacks. Plus, these types are more for internal use, and we don't really guarantee their stability since you are supposed to only be using the user facing apis. For navigating between pages, you are better of calling the navigate function returned by the useNavigate hook.
const navigate = useNavigate()

navigate({ to: '/foo/bar' })
const navigate = useNavigate()

navigate({ to: '/foo/bar' })
adverse-sapphire
adverse-sapphireOP2y ago
@Sean Cassiere Thanks.

Did you find this page helpful?