Repository navigation
feat(pages): type useParams() from the page's URL pattern - #685
Conversation
|
Note that this PR adds runtime checks to I'm not sure if we want to do runtime checks within If we're ok with just typechecking, consider this instead: useParams<'/posts/:id'>();or use your newly-added useParams<PageParams<'/posts/:id'>>();Since |
|
I also prefer doing typechecking only and not failing during runtime for this. |
|
That makes sense, thanks for the insight! I'll make this static-check only |
`useParams<'/users/:id'>()` now returns `{ id: string }` in all four
adapters. The pattern must be one of the app's pages, so a misspelled
param or page is a type error. This is a type-only change: the params
are returned as before, with no runtime check.
- The generated `.void/routes.d.ts` adds `PagePathMap` (page patterns
and their param names, without HTTP or WebSocket routes), plus
`PagePath` and `PageParams<P>`. `void/routes` declares the same types
for apps without generated declarations.
- An unnamed catch-all (`[...]`) has no param key, matching
`c.req.param()`. A union of patterns gives a union of params.
- `useParams()` and `useParams<{ id: string }>()` keep their types.
a27aaf1 to
a616364
Compare
The conditional return type broke generic wrappers such as
`function f<T extends Record<string, string>>(): T { return useParams<T>(); }`,
and `ReturnType<typeof useParams>` included `{}` for static pages. Use
overloads instead: the record generic first, then the page pattern, then
a plain `Record<string, string>` signature for `ReturnType`.
|
Ok, switched to type-check only, and I confirmed that the existing behavior (no type param, or non-path type param such as |
Pass a page's URL pattern as the type argument of
useParams()to type its params.useParams()anduseParams<{ id: string }>()are unchanged, and no config flag is needed.void/routesexportsPagePathMap,PagePathandPageParams<P>. Both the generated.void/routes.d.tsand the package declare them.