Skip to content

Commit

Permalink
fix(reactiveComputed): unwrap reactive type
Browse files Browse the repository at this point in the history
  • Loading branch information
sxzz committed Jul 6, 2023
1 parent bddfbae commit c33bd6e
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 9 deletions.
5 changes: 3 additions & 2 deletions packages/shared/reactiveComputed/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { isVue2, nextTick, ref, watch, watchEffect } from 'vue-demi'
import { describe, expect, it } from 'vitest'
import { describe, expect, expectTypeOf, it } from 'vitest'
import { reactiveComputed } from '.'

describe('reactiveComputed', () => {
Expand All @@ -8,9 +8,10 @@ describe('reactiveComputed', () => {

const state = reactiveComputed(() => {
return {
count: count.value,
count,
}
})
expectTypeOf(state).toEqualTypeOf<{ count: number }>()

expect(state.count).toBe(0)

Expand Down
2 changes: 1 addition & 1 deletion packages/shared/reactiveComputed/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import { toReactive } from '../toReactive'
/**
* Computed reactive object.
*/
export function reactiveComputed<T extends {}>(fn: () => T): T {
export function reactiveComputed<T extends {}>(fn: () => T) {
return toReactive(computed(fn))
}
13 changes: 7 additions & 6 deletions packages/shared/toReactive/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// eslint-disable-next-line no-restricted-imports
import { isRef, reactive, unref } from 'vue-demi'
import type { UnwrapNestedRefs } from 'vue-demi'
import { isRef, reactive } from 'vue-demi'
import { toValue } from '../toValue'
import type { MaybeRef } from '../utils'

/**
Expand All @@ -10,13 +11,13 @@ import type { MaybeRef } from '../utils'
*/
export function toReactive<T extends object>(
objectRef: MaybeRef<T>,
): T {
): UnwrapNestedRefs<T> {
if (!isRef(objectRef))
return reactive(objectRef) as T
return reactive(objectRef)

const proxy = new Proxy({}, {
get(_, p, receiver) {
return unref(Reflect.get(objectRef.value, p, receiver))
return toValue(Reflect.get(objectRef.value, p, receiver))
},
set(_, p, value) {
if (isRef((objectRef.value as any)[p]) && !isRef(value))
Expand All @@ -42,5 +43,5 @@ export function toReactive<T extends object>(
},
})

return reactive(proxy) as T
return reactive(proxy) as UnwrapNestedRefs<T>
}

0 comments on commit c33bd6e

Please sign in to comment.