router icon indicating copy to clipboard operation
router copied to clipboard

TS error when using redirect in a loader

Open el-dav opened this issue 2 years ago • 1 comments

Describe the bug

When returning a redirect from a loader I am getting a weird TS error:

'router' is referenced directly or indirectly in its own type annotation.

This then messes up the types for the rest of the project as Register.router is typed as any. In the minimal example linked it's just a single error, but in a real project this issue permeates through to the rest of the application.

The error is pretty weird though. If I retype the to value for the redirect then it goes away (although only in this simplified example).

You also get the same issue when doing the same steps with the beforeLoad option

Your Example Website or App

https://stackblitz.com/edit/stackblitz-starters-fz4jr4?file=src%2FRoutes.tsx

Steps to Reproduce the Bug or Issue

  1. Go to the linked stackblitz
  2. In your editor you should see a TS error on the line router: typeof router; within the declaration with the error: 'router' is referenced directly or indirectly in its own type annotation.`

Expected behavior

As a user I expected not to have a TS error from this usage

Screenshots or Videos

No response

Platform

NA

Additional context

I've included that actual code below:

import React from 'react';
import {
  RootRoute,
  Route,
  Router,
  RouterProvider,
  redirect,
  Outlet,
} from '@tanstack/react-router';

const nestedRoute = new Route({
  path: '/nested',
  getParentRoute: () => rootRoute,
  component: () => <h1>Nested</h1>,
});

export const indexRoute = new Route({
  path: '/',
  getParentRoute: () => rootRoute,
  component: () => <h1>Index</h1>,
  loader: () => {
    // This line seems to be causing the TS error
    return redirect({
      to: '/nested',
    });
  },
});

export const rootRoute = new RootRoute({
  component: () => (
    <div>
      <h1>My App</h1>
      <Outlet />
    </div>
  ),
});

const routeTree = rootRoute.addChildren([indexRoute, nestedRoute]);

const router = new Router({ routeTree });

declare module '@tanstack/react-router' {
  interface Register {
    // Below line has the TS error: 'router' is referenced directly or indirectly in its own type annotation.
    router: typeof router;
  }
}

export const AppRouteProvider = () => {
  return <RouterProvider router={router} />;
};

el-dav avatar Jan 12 '24 12:01 el-dav

you need to throw the redirect: https://stackblitz.com/edit/stackblitz-starters-szxbkh?file=src%2FRoutes.tsx

schiller-manuel avatar Jan 12 '24 21:01 schiller-manuel

Thanks, I can see you've also updated the docs to remove the return example here

Much appreciated, will close this issue

el-dav avatar Jan 14 '24 12:01 el-dav