Skip to content

Commit

Permalink
fix(types): make toRef return correct type(fix #4732) (#4734)
Browse files Browse the repository at this point in the history
* fix(types): make `toRef` return correct type(fix #4732)

* chore: use correct test

Co-authored-by: Evan You <yyx990803@gmail.com>
  • Loading branch information
caozhong1996 and yyx990803 authored Oct 8, 2021
1 parent f66d456 commit 925bc34
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
6 changes: 4 additions & 2 deletions packages/reactivity/src/ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ export function isRef(r: any): r is Ref {
return Boolean(r && r.__v_isRef === true)
}

export function ref<T extends object>(value: T): ToRef<T>
export function ref<T extends object>(
value: T
): [T] extends [Ref] ? T : Ref<UnwrapRef<T>>
export function ref<T>(value: T): Ref<UnwrapRef<T>>
export function ref<T = any>(): Ref<T | undefined>
export function ref(value?: unknown) {
Expand Down Expand Up @@ -212,7 +214,7 @@ class ObjectRefImpl<T extends object, K extends keyof T> {
}
}

export type ToRef<T> = [T] extends [Ref] ? T : Ref<UnwrapRef<T>>
export type ToRef<T> = [T] extends [Ref] ? T : Ref<T>
export function toRef<T extends object, K extends keyof T>(
object: T,
key: K
Expand Down
13 changes: 13 additions & 0 deletions test-dts/ref.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
toRef,
toRefs,
ToRefs,
shallowReactive,
watch
} from './index'

Expand Down Expand Up @@ -236,3 +237,15 @@ function testUnrefGenerics<T>(p: T | Ref<T>) {
}

testUnrefGenerics(1)

// #4732
const baz = shallowReactive({
foo: {
bar: ref(42)
}
})

const foo = toRef(baz, 'foo')

expectType<Ref<number>>(foo.value.bar)
expectType<number>(foo.value.bar.value)

0 comments on commit 925bc34

Please sign in to comment.