After the introduction of Variant Accessors in the latest version of TypeScript (TS 5.1), my interest peaked in creating composables like the one below:
export function useRouteQueryParam(param: MaybeRef<string>): WritableComputedRef<string | null>
export function useRouteQueryParam(param: MaybeRef<string>, defaultValue: string): WritableComputedRef<string>
export function useRouteQueryParam(param: MaybeRef<string>, defaultValue?: string): WritableComputedRef<string | null> {
const paramRef = ref(param)
const route = useRoute()
const router = useRouter()
return computed({
get() {
const [value] = asArray(route.query[paramRef.value])
return value ?? defaultValue ?? null
},
set(value) {
const query = { ...route.query, [paramRef.value]: value }
router.push({ query })
},
})
}
In this scenario, it would be ideal to utilize variant accessors for the WritableComputedRef
when a defaultValue
is provided by the caller. The expectation is that the get function should always return a string
, while still allowing the set function to accept either a string
or null
. However, due to the current syntax limitations of WritableComputedRef
which only allows for a single type T
, I am doubtful if this setup is feasible at the moment.