]> git.ipfire.org Git - thirdparty/vuejs/pinia.git/commitdiff
fix(types): handle union types in generic parameter (#2794)
authorTycho <jh.leong@outlook.com>
Sun, 6 Oct 2024 14:48:58 +0000 (22:48 +0800)
committerGitHub <noreply@github.com>
Sun, 6 Oct 2024 14:48:58 +0000 (16:48 +0200)
Fix #2785

packages/pinia/src/storeToRefs.ts
packages/pinia/test-dts/store.test-d.ts

index 8d9cbe6ecfc9f475e5f9f5c3bbf9d44692e3b574..5b268fc991c2e2d03c5c203736388e77514cdb99 100644 (file)
@@ -68,9 +68,11 @@ type _ToStateRefs<SS> =
  * Extracts the return type for `storeToRefs`.
  * Will convert any `getters` into `ComputedRef`.
  */
-export type StoreToRefs<SS extends StoreGeneric> = _ToStateRefs<SS> &
-  ToRefs<PiniaCustomStateProperties<StoreState<SS>>> &
-  _ToComputedRefs<StoreGetters<SS>>
+export type StoreToRefs<SS extends StoreGeneric> = SS extends unknown
+  ? _ToStateRefs<SS> &
+      ToRefs<PiniaCustomStateProperties<StoreState<SS>>> &
+      _ToComputedRefs<StoreGetters<SS>>
+  : never
 
 /**
  * Creates an object of references with all the state, getters, and plugin-added
index 3d90a66abf44940c5b4e833aca6e7281af090252..b8d9abde413d35e1d41e137d0439a148cf7a897d 100644 (file)
@@ -5,7 +5,7 @@ import {
   expectType,
   storeToRefs,
 } from './'
-import { computed, ref, UnwrapRef, watch } from 'vue'
+import { computed, Ref, ref, UnwrapRef, watch, WritableComputedRef } from 'vue'
 
 const useStore = defineStore({
   id: 'name',
@@ -328,3 +328,12 @@ expectType<number>(refs.bananasAmount.value)
 refs.bananasAmount.value = 0
 // @ts-expect-error: this one is readonly
 refs.total.value = 0
+
+const refStore = defineStore('ref-bananas', () => {
+  const bananas = ref(['banana1', 'banana2'])
+  return { bananas }
+})()
+declare const conditionalStore: typeof refStore | typeof writableComputedStore
+expectType<Ref<string[]> | WritableComputedRef<'banana'[]>>(
+  storeToRefs(conditionalStore).bananas
+)