vuejs / router

🚦 The official router for Vue.js
https://router.vuejs.org/
MIT License
3.75k stars 1.15k forks source link

Custom Query Parsing Doesn't Mesh Well With Typescript #2165

Closed klondikemarlen closed 4 months ago

klondikemarlen commented 4 months ago

Reproduction

Unknown

Steps to reproduce the bug

When using vue-router with qs.parse with Typescript I need to ignore the parseQuery typing.

I'm using

import qs, { type ParsedQs } from "qs"

export { type ParsedQs }

export function stringifyQuery(params: unknown): string {
  return qs.stringify(params, {
    arrayFormat: "brackets",
    strictNullHandling: true,
  })
}

export function parseQuery(search: string): ParsedQs {
  return qs.parse(search, {
    strictNullHandling: true,
  })
}

const routes = [
// some routes
]

const router = createRouter({
  history: createWebHistory(),
  // @ts-expect-error - Ignore router query format as Qs format is more flexible
  parseQuery,
  stringifyQuery,
  routes,
})

There is an additional irritation in that the types don't mesh in Vuetify HTML either.

e.g.

<template>
<!-- Some form with some fields for searching datasets -->
<v-btn
  :to="{ name: 'DatasetsPage', query: searchQuery }"
  >Search</v-btn
>
</template>

<script lang="ts" setup>
import { computed, ref } from "vue"

const keywords = ref<string[]>([])
const departmentId = ref<number>()

/**
 * As we are parsing with Qs, we are ignoring the invalid type information
 */
const searchQuery = computed(() => {
  return {
    where: {
      departmentId: departmentId.value,
      keywords: keywords.value,
    },
  } as unknown as LocationQueryRaw
})
</script>

Expected behavior

I would expect vue-router to either support passing in a custom type for parseQuery or auto-magically propagate the type returned by whatever function you pass to parseQuery.

Actual behavior

vue-router uses it's own LocationQueryRaw type which does not mesh well with custom query parsers. This problem may also exist in Vuetify's VBtn#to, but it seems likely to me that vue-router would need to fix their typing first in either case.

Additional information

No response

klondikemarlen commented 4 months ago

@posva Is vue-router dropping Typescript support? I'd love to be able to tell my boss, so that I don't have to work with it either.

posva commented 4 months ago

This is indeed a technical limitation. You will have to cast, ignore, or use functions to generate the types that are convenient to you

posva commented 4 months ago

Apparently I didn't click send the comment. Fortunately, it was kept saved in local storage so I just sent it again 😄

@posva Is vue-router dropping Typescript support? I'd love to be able to tell my boss, so that I don't have to work with it either.

In the future, refrain from snarky comments like this. Thank you.