posva / pinia-colada

🍹 The smart data fetching layer for Pinia
https://pinia-colada.esm.dev/
MIT License
761 stars 10 forks source link

Refactor types to use a union for better type narrowing #18

Closed posva closed 2 months ago

posva commented 6 months ago

TS now supports type narrowing when destructuring. So it's worth having multiple types for the return values of useQuery and useMutation

import { Ref, ShallowRef, ref, shallowRef } from "vue";

interface UseStuffReturnOn<T> {
  state: Ref<'on'>
  data: ShallowRef<T>
}

interface UseStuffReturnOff<T> {
  state: Ref<'off'>
  data: ShallowRef<T | undefined>
}

type UseStuffReturn<T> = UseStuffReturnOff<T> | UseStuffReturnOn<T>

export function useStuff<T>(initial: T): UseStuffReturn<T> {
  return {
    state: ref('on'),
    data: shallowRef(initial)
  }
}

const { data, state } = useStuff(0)

if (state.value === 'on') {
  data.value.toFixed()
}
posva commented 4 months ago

This doesn't work with strict 😅 Demo

Maybe a solution is adding a new property state that contains the whole state raw. This would require an internal refactor to contain the whole state as one

posva commented 2 months ago

A new object state is added to useQuery() to hold data, error, and status