WoJ
WoJ

Reputation: 29995

How to access dynamic route parameters as strings?

I have in my project a route set up as

  {
    path: '/change/:who',
    component: () => import('layouts/ChangeValue.vue'),
  },

When in the ChangeValue component, with the route http://localhost:8080/#/change/michael, I tried to access the :who parameter (which should be michael):

  setup() {
    let user = ref<string>('');
    let route = useRoute();
    user.value = route.params.who;
(...)

This raises an error at compilation time:

index.js?a29e:529 [webpack-dev-server] TS2322: Type 'string | string[]' is not assignable to type 'string'.
  Type 'string[]' is not assignable to type 'string'.
    19 |     let user = ref<string>('');
    20 |     let route = useRoute();
  > 21 |     user.value = route.params.who;
       |     ^^^^^^^^^^
    22 |
    23 |
    24 |     interface CorveesDescI {

My main problem is that I do not understand why the type of route.params.who is expected to be string[] and not simply string.

Now, I tried to take the first element of route.params.who, and it is the letter m (the first letter of michael, or a[0] if a = michael).

So I have


Note: the framework is Quasar, but I do not think it is relevant

Upvotes: 0

Views: 845

Answers (1)

Michal Lev&#253;
Michal Lev&#253;

Reputation: 37833

Problem is that creating type descriptions for route params is hard.

Route dynamic params can be defined using custom regex which allows matching single as well as repeatable params. Typing this dynamically (to your specific route definition) is not possible. That's why route params type is declared as Record<string, string | string[]>

To solve your problem, just use type casting:

user.value = route.params.who as string

Upvotes: 1

Related Questions