Document: How can I use typescript to annotate the type of useRoute().params?
Describe the feature
I want to use useRoute in typescript, but there is no documentation for it. useRoute seems to be a generic function, but I don't know how to write it in such a way that it defines the type of params. I think it is necessary to add the appropriate description and code examples to the documentation.
Additional information
- [X] Would you be willing to help implement this feature?
- [ ] Could this feature be implemented as a module?
Final checks
- [X] Read the contribution guide.
- [X] Check existing discussions and issues.
Maybe we can automatically generate the type of params from the page's directory structure?
There is an experimental flag you can use to get the typed params already :)
https://nuxt.com/blog/v3-5#fully-typed-pages
oh, in my case, the type define is: Record<never, never> | { locale: string; } | { locale: string; slug?: ParamValueZeroOrMore<false>; } | { locale: string; slug?: ParamValueZeroOrMore<false>; }
There will be a Record<never, never> present that prevents me from using params.locale directly.
How do I fix this?
Don't follow you. Can you give me more context of how things are set up for you?
How to fix this?
You need to pass in the name to get type safe access for the current page - so useRoute('my-route').
You need to pass in the name to get type safe access for the current page - so
useRoute('my-route').
What is the correct way to use this in definePageMeta.validate?
You need to pass in the name to get type safe access for the current page - so
useRoute('my-route').What is the correct way to use this in
definePageMeta.validate?
I just learned about validate option, so thanks :) The way I would use it, given it returns a boolean and it will provide the route, I would check with simple
validate: async (route) => { return Object.hasOwn(route.params, 'slug') },
You need to pass in the name to get type safe access for the current page - so
useRoute('my-route').What is the correct way to use this in
definePageMeta.validate?
For definePageMeta.validate I'm using this (with the experimental typedPages enabled):
validate: async (route) => {
// Check if the clientId is made up of digits
return 'clientId' in route.params && /^\d+$/.test(route.params.clientId)
},