reactjstypescriptvitetanstacktanstack-router

@tanstack/react-router (Typescript) - how to get the string of union types that's auto-generated for Link.to prop?


Just like the title! The typescript support with tanstack is a lifesaver, but I would like to know how to get the actual type for the generated route paths.

For example, there's typescript support for the <Link to="/some-route">. Is there any way to get the type of the to prop?

I tried importing and playing around with other types from @tanstack/react-router, but couldn't find anything. I also could not find any documentation on this.


Solution

  • Tanstack Router can automatically generate a route tree file that includes types related to routing. I created an example app using command: npm create @tanstack/router@latest, and I found the following code in src/routeTree.gen.ts:

    export interface FileRoutesByTo {
      '/': typeof IndexRoute
      '/about': typeof AboutRoute
    }
    

    This file is automatically updated when new files are added under the route directory while Vite is running. The routing file setup is handled in vite.config.ts using TanStackRouterVite() plugin:

    export default defineConfig({
      plugins: [TanStackRouterVite({}), react()],
    })
    

    For example, you can customize the name of the generated route tree file by using the generatedRouteTree option. (the default is src/routeTree.gen.ts)

    Note: This explanation applies to File-Based Routing. Other routing methods might have different configurations.


    edited:

    Wrapper component example:

    type extendedLinkProps = Omit<LinkProps, "to"> & {
      to: string
    }
    
    type toType = LinkProps['to'];
    function isToType(value: any): value is toType {
      // Add appropriate type checks here.
      return true;
    }
    
    export const ExtendedLink = ({to, children, ...linkProps}: extendedLinkProps) => {
      const path = convertToToPath(to); // e.g. "/example/$id"
      const param = convertToToParam(to); // e.g. "1"
      type toType = LinkProps['to'];
      if (!isToType(path)) return;
      return <Link {...linkProps} to={path} params={param}>{children}</Link>
    }
    

    use it like:

    <ExtendedLink to="/example/1">
      example
    </ExtendedLink>
    

    I think it works, but has not been tested.