Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
posva opened this issue Mar 18, 2024 — with Volta.net · 1 comment
Open

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

posva opened this issue Mar 18, 2024 — with Volta.net · 1 comment
Labels
⚡️ enhancement improvement over an existing feature typescript issue related to types

Comments

Copy link
Owner

posva commented Mar 18, 2024

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 posva added typescript issue related to types ⚡️ enhancement improvement over an existing feature labels Mar 18, 2024 — with Volta.net
@posva
Copy link
Owner Author

posva commented May 16, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
⚡️ enhancement improvement over an existing feature typescript issue related to types
Projects
Status: Todo
Development

No branches or pull requests

1 participant