I am currently working on a Nuxt.js project with TypeScript and am facing an issue with route query parameters. The specific problem arises when TypeScript throws a type error related to a route query parameter called userType.
The issue occurs when I attempt to pass userType as a query parameter in a NuxtLink component:
<NuxtLink
:to="localePath({ name: 'account-upload-images', query: { userType: retrievedUserType } })"
class="skip-for-now"
>
{{ $t('sign_up.cta.skip_for_now.label') }}
</NuxtLink>
Here, retrievedUserType is a computed property that should be a string. The error message points to this line, stating: "Type 'unknown' is not assignable to type 'string | (string | null)[] | null | undefined'."
To set the userType route query parameter, I have a function getSignedUpAs that consistently returns a string:
const getSignedUpAs = (): string => {
return formData.signed_up_as.split('--')[0];
};
const userType = getSignedUpAs();
router.push({
name: 'account-instagram-approval',
query: { userType: userType },
});
When trying to retrieve userType from the route query in the account-instagram-approval component:
<script lang="ts">
import { computed, defineComponent, ref, useRoute } from
'@nuxtjs/composition-api';
export default defineComponent({
name: 'account-instagram-approval',
setup() {
const route = useRoute();
const retrievedUserType = computed(() => {
return route.value.query.userType as string;
});
return { retrievedUserType };
},
});
</script>
Despite trying various solutions, such as explicit type casting and initializing retrievedUserType with an empty string, the TypeScript error persists. I need assistance in understanding why this error occurs and finding a resolution. Any suggestions or alternative approaches to handle route query parameters with TypeScript in Nuxt/Vue would be greatly appreciated.
I have observed that when I include the type in my template:
<NuxtLink
:to="localePath({ name: 'account-upload-images', query: { userType: retrievedUserType as string } })"
class="skip-for-now"
>
{{ $t('sign_up.cta.skip_for_now.label') }}
</NuxtLink>
Visual Studio Code no longer throws an error, but when running the app, I encounter the following error:
Errors compiling template:
invalid expression: Unexpected identifier in
localePath({ name: 'account-upload-images', query: { userType: retrievedUserType as string } })
Despite casting my query param as a string everywhere, TypeScript still interprets it as "unknown." This inconsistency is causing confusion and I would appreciate any insights on how to rectify this issue.