Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions packages/pinia/src/storeToRefs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does this fix the problem? Isn't x extends unknown always true? I want to add a note comment for my future self and other contributors
TS is sometimes so weird 🫠

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When conditional types act on a generic type, they become distributive when given a union type (Distributive Conditional Types).

In this case, it will always resolve to the first branch because unknown is the top type in TypeScript.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! This makes me wonder if there isn't another bug up the chain of types. But this is already good enough!

? _ToStateRefs<SS> &
ToRefs<PiniaCustomStateProperties<StoreState<SS>>> &
_ToComputedRefs<StoreGetters<SS>>
: never

/**
* Creates an object of references with all the state, getters, and plugin-added
Expand Down
11 changes: 10 additions & 1 deletion packages/pinia/test-dts/store.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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
)