fenok / react-router-typesafe-routes

Comprehensive and extensible type-safe routes for React Router v6 with first-class support for nested routes and param validation.
MIT License
145 stars 3 forks source link

For path `'/'` error TS2345: Argument of type 'string' is not assignable to parameter of type 'never'. #18

Closed brunofin closed 1 year ago

brunofin commented 1 year ago

Hi, when I try to use the path value '/' for a route I get the error:

TS2345: Argument of type 'string' is not assignable to parameter of type 'never'. 

This happens only for this value. Feels like there's an explicit check for this value in particular, but I wonder why since I have been always able to use it without issues with react-router?

export const ROUTES = {
  DEFAULT: route('/'), // <- TS2345: Argument of type 'string' is not assignable to parameter of type 'never'. 
};
<Routes>
    <Route
        path={'/'}  // <- not a problem
        element={<MyComponent />}
    />
brunofin commented 1 year ago

might be related with this type definition https://github.com/fenok/react-router-typesafe-routes/blob/main/src/common/createRoute/createRoute.ts#L48

brunofin commented 1 year ago

now I see the issue is with any route that starts with a backslash

fenok commented 1 year ago

Hello! This is actually intentional. You're hitting a safeguard that prevents leading or trailing slashes in the path argument of route. Granted, it's a bit confusing, but I'm not sure how to make the error message more user-friendly.

The path argument of React Router <Route/> is not a 1-to-1 match to the path argument of the library route. Quoting from the README:

The path argument is what you would put to the path property of a <Route/>, but without leading or trailing slashes (/).

The reason for this is that in the case of the library route, the leading / doesn't do anything. We don't put this value to <Route/> directly. Instead, we put there either route('segment').path or route('segment').relativePath. Therefore, the leading / is banned to reduce confusion and emphasize that the "relativeness" of the route is determined solely by .path or .relativePath usage.

The trailing / is banned because a) it's purely cosmetic and b) it's a bit easier to simply join the provided values with a / than to check for the trailing (or leading) / existence.

In your case, you should use an empty string instead of '/'. That is, route('').path is equivalent to '/'.

fenok commented 1 year ago

I'm closing this because it seems to work as intended. I mentioned this quirk in the "Limitations" section in README.

Please reopen if I'm missing something.

fenok commented 1 year ago

Addressed in https://github.com/fenok/react-router-typesafe-routes/pull/31