Change type of typed params
I am wondering how I can change the type of the typed params. Currently, it's always set to string, but I have an ID that is a number. How can I define that this ID is a number
2 Replies
Hi @L E L P. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
To change the type of typed params in Nuxt, particularly for route parameters like an ID, you can use a custom regular expression in your route definition. This allows you to specify that a parameter should be a number instead of the default string type. Here's how you can do it:
1. In your page component, use
definePageMeta
to set a custom path with a regular expression:
This regular expression (\\d+)
ensures that the id
parameter only matches one or more digits, effectively making it a number.
2. You can also use the validate
option in definePageMeta
to further ensure type safety:
By using these approaches, you can ensure that the id
parameter is treated as a number rather than a string.
It's important to note that while this method enforces number-like values for the route parameter, TypeScript might still infer it as a string in some cases. If you need strict typing, you may need to cast the parameter to a number when using it in your component logic.
Nuxt Documentation - definePageMeta (https://nuxt.com/docs/api/utils/define-page-meta#meta)
Remember that this approach affects how the route is matched and validated, ensuring that only numeric IDs will be accepted for that route.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@447376335623421975> Kapa.ai is still learning and improving, please let me know how I did by reacting below.