N
Nuxt3w ago
L E L P

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
No description
2 Replies
kapa.ai
kapa.ai3w ago
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:
definePageMeta({
path: '/users/:id(\\d+)'
})
definePageMeta({
path: '/users/:id(\\d+)'
})
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:
definePageMeta({
validate: (route) => {
return /^\d+$/.test(route.params.id as string)
}
})
definePageMeta({
validate: (route) => {
return /^\d+$/.test(route.params.id as string)
}
})
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: ----------------------
kapa.ai
kapa.ai3w ago
<@447376335623421975> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Want results from more Discord servers?
Add your server