nuxt icon indicating copy to clipboard operation
nuxt copied to clipboard

Document: How can I use typescript to annotate the type of useRoute().params?

Open Jannchie opened this issue 2 years ago • 7 comments

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

Jannchie avatar Jul 12 '23 10:07 Jannchie

Maybe we can automatically generate the type of params from the page's directory structure?

Jannchie avatar Jul 12 '23 10:07 Jannchie

There is an experimental flag you can use to get the typed params already :)

https://nuxt.com/blog/v3-5#fully-typed-pages

prashantpalikhe avatar Jul 12 '23 10:07 prashantpalikhe

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?

Jannchie avatar Jul 12 '23 11:07 Jannchie

Don't follow you. Can you give me more context of how things are set up for you?

prashantpalikhe avatar Jul 12 '23 14:07 prashantpalikhe

image How to fix this?

Jannchie avatar Jul 12 '23 14:07 Jannchie

You need to pass in the name to get type safe access for the current page - so useRoute('my-route').

danielroe avatar Jul 12 '23 17:07 danielroe

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?

blasdfaa avatar Feb 08 '24 15:02 blasdfaa

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') },

milos018 avatar Feb 22 '24 00:02 milos018

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)
},

elwinvaneede avatar Mar 04 '24 14:03 elwinvaneede