How to use generated "Route<T>" type (from "typedRoutes") with dynamic routes #69018
Unanswered
borispetrovdev
asked this question in
App Router
Replies: 1 comment
-
You have to also provide the string as a parameter to the const typedRoute: Route<'/dynamic/foo'> = '/dynamic/foo'; when the Route type is used in context (e.g. in the Also, I’d recommend using const typedRoute = '/dynamic/foo' satisfies Route<'/dynamic/foo'>; If you want to simplify the syntax so that the type parameter can be inferred in context, you could make a function that infers the type parameter: function typedRoute<T extends string>(route: Route<T>) {
return route;
}
const myRoute = typedRoute('/dynamic/foo');
// myRoute has type Route<'/dynamic/foo'>, and will error if an invalid route is passed |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
TL;DR: In the following example code, why am I getting the error
"/dynamic/foo"' is not assignable to type 'Route'
, despite the existence of the route/dynamic/[some_param]
?Details: I'm trying to achieve type-safe
redirect
(andrevalidatePath
) calls using the experimentaltypedRoutes
feature. SincetypedRoutes
doesn't automatically ensure that strings passed toredirect
correspond to existing routes (it seems to only type-check thehref
prop of<Link>
), I am declaring atypedRoute: Route
variable and then passing it toredirect
. However, I'm getting a typescript error essentially saying that the string I've assigned totypedRoute
is not a validRoute
.As you can see in the folder structure pictured in the screenshot above, I have a route
/dynamic/[some_param]
, so the string"/dynamic/foo"
should indeed be a validRoute
. In fact, when I inspect theRoute<T>
type, I see/dynamic/$__next_route_internal_types_SafeSlug<infer _ extends string>}
, so the route is correctly detected bytypedRoutes
, but I can't seem to access it when I'm assigning types (and values) to variables:Ideally, I would write
const typedRoute: Route = "/dyna"
and get an autocomplete saying/dynamic/${string}
. What am I missing?Beta Was this translation helpful? Give feedback.
All reactions