T
TanStack•2y ago
hilarious-sapphire

Infer valid "to" types for a root router instance

Hi, How would I retrieve the "to" field to use in a TS type definition for my applications router? The use case I have is I have my Button component, which can double as a link, and I want to include to /from in it's props. I want to get the typing that I would normally get from the native <Link> and useNavigate functions.
7 Replies
wise-white
wise-white•2y ago
do you also need to pass in search / path params?
hilarious-sapphire
hilarious-sapphireOP•2y ago
@Manuel Schiller Yeah, I would want to require those as well, since it would be part of the link
flat-fuchsia
flat-fuchsia•2y ago
good question. I'm also looking into how I can structure my types better
wise-white
wise-white•2y ago
Yep, I would like this too! I had this solution working for me below. It made it possible to get auto-completion on valid links in my project, but it stopped working for me after upgrading from 1.28.1 to 1.32.5.
import type { ToOptions } from "@tanstack/react-router"

type ExtractString<T> = T extends string ? T : never

export type TValidToOption = ExtractString<ToOptions["to"]>
import type { ToOptions } from "@tanstack/react-router"

type ExtractString<T> = T extends string ? T : never

export type TValidToOption = ExtractString<ToOptions["to"]>
Whenever using a function like this I'd get auto-complete
<CoolLink link="/very-very-long-route-path-thank-god-i-have-auto-complete" />
<CoolLink link="/very-very-long-route-path-thank-god-i-have-auto-complete" />
import type { TValidToOption } from "cool-types"
import {Link} from "@tanstack/react-router"

function CoolLink({link}: {link: TValidToOption}) {
return <Link to={link}>So cool link</Link>
}
import type { TValidToOption } from "cool-types"
import {Link} from "@tanstack/react-router"

function CoolLink({link}: {link: TValidToOption}) {
return <Link to={link}>So cool link</Link>
}
wise-white
wise-white•2y ago
you should be able to use the createLink function
wise-white
wise-white•2y ago
Is createLink documented anywhere? Can't find it 🤔
wise-white
wise-white•2y ago
not yet, it is still quite experimental have a look at e.g. https://discord.com/channels/719702312431386674/1237372623210676254/1237379300026748941

Did you find this page helpful?