]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
fix(types): make `toRef` return correct type(fix #4732) (#4734)
authorChe Guevara <836934184@qq.com>
Fri, 8 Oct 2021 15:57:49 +0000 (23:57 +0800)
committerGitHub <noreply@github.com>
Fri, 8 Oct 2021 15:57:49 +0000 (11:57 -0400)
* fix(types): make `toRef` return correct type(fix #4732)

* chore: use correct test

Co-authored-by: Evan You <yyx990803@gmail.com>
packages/reactivity/src/ref.ts
test-dts/ref.test-d.ts

index a4a69b1f1888a3a222db8d195aa2f953089a22b9..f33375824fef6ea3320b29a565d1584acc92fa78 100644 (file)
@@ -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) {
@@ -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
index c7f1283720ed5d77fdadc1245ea388e6e4ea2408..8129d6182e91e2ccc8ecf68490210b164ad6ff0a 100644 (file)
@@ -10,6 +10,7 @@ import {
   toRef,
   toRefs,
   ToRefs,
+  shallowReactive,
   watch
 } from './index'
 
@@ -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)