From: Ben Jones Date: Wed, 28 Dec 2022 21:21:55 +0000 (+0000) Subject: fix(types): type storeToRefs getters as ComputedRef (#1898) X-Git-Tag: pinia@2.0.29~3 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=dcf7ef0d3a6773da97c5cdde4b9a958492a15d7d;p=thirdparty%2Fvuejs%2Fpinia.git fix(types): type storeToRefs getters as ComputedRef (#1898) Closes https://github.com/vuejs/pinia/issues/1852 --- diff --git a/packages/pinia/src/storeToRefs.ts b/packages/pinia/src/storeToRefs.ts index fc294d31..76e91c33 100644 --- a/packages/pinia/src/storeToRefs.ts +++ b/packages/pinia/src/storeToRefs.ts @@ -1,8 +1,11 @@ import { + ComputedRef, isReactive, isRef, isVue2, + Ref, toRaw, + ToRef, toRef, ToRefs, toRefs, @@ -10,6 +13,21 @@ import { import { StoreGetters, StoreState } from './store' import type { PiniaCustomStateProperties, StoreGeneric } from './types' +type ToComputedRefs = { + [K in keyof T]: ToRef extends Ref + ? ComputedRef + : ToRef +} + +/** + * Extracts the return type for `storeToRefs`. + * Will convert any `getters` into `ComputedRef`. + */ +export type StoreToRefs = ToRefs< + StoreState & PiniaCustomStateProperties> +> & + ToComputedRefs> + /** * Creates an object of references with all the state, getters, and plugin-added * state properties of the store. Similar to `toRefs()` but specifically @@ -20,9 +38,7 @@ import type { PiniaCustomStateProperties, StoreGeneric } from './types' */ export function storeToRefs( store: SS -): ToRefs< - StoreState & StoreGetters & PiniaCustomStateProperties> -> { +): StoreToRefs { // See https://github.com/vuejs/pinia/issues/852 // It's easier to just use toRefs() even if it includes more stuff if (isVue2) { @@ -31,11 +47,7 @@ export function storeToRefs( } else { store = toRaw(store) - const refs = {} as ToRefs< - StoreState & - StoreGetters & - PiniaCustomStateProperties> - > + const refs = {} as StoreToRefs for (const key in store) { const value = store[key] if (isRef(value) || isReactive(value)) { diff --git a/packages/pinia/test-dts/customizations.test-d.ts b/packages/pinia/test-dts/customizations.test-d.ts index bab6afe1..ebf3b643 100644 --- a/packages/pinia/test-dts/customizations.test-d.ts +++ b/packages/pinia/test-dts/customizations.test-d.ts @@ -6,7 +6,7 @@ import { _ActionsTree, storeToRefs, } from './' -import { App, ref, Ref } from 'vue' +import { App, computed, ComputedRef, ref, Ref } from 'vue' declare module '../dist/pinia' { export interface MapStoresCustomization { @@ -159,7 +159,7 @@ expectType<{ a: Ref; myState: Ref; stateOnly: Ref }>( expectType<{ n: Ref - double: Ref + double: ComputedRef myState: Ref stateOnly: Ref }>( @@ -172,3 +172,21 @@ expectType<{ })() ) ) + +expectType<{ + n: Ref + double: ComputedRef + myState: Ref + stateOnly: Ref +}>( + storeToRefs( + defineStore('a', () => { + const n = ref(1) + const double = computed(() => n.value * 2) + return { + n, + double + } + })() + ) +)