Explorar el Código

fix(types/ref): handle nested refs in UnwrapRef (#12049)

close #12044
Tycho hace 1 año
padre
commit
e2c19c20cf
Se han modificado 2 ficheros con 23 adiciones y 3 borrados
  1. 18 0
      packages-private/dts-test/ref.test-d.ts
  2. 5 3
      packages/reactivity/src/ref.ts

+ 18 - 0
packages-private/dts-test/ref.test-d.ts

@@ -189,6 +189,24 @@ describe('allow getter and setter types to be unrelated', <T>() => {
   f.value = ref(1)
 })
 
+describe('correctly unwraps nested refs', () => {
+  const obj = {
+    n: 24,
+    ref: ref(24),
+    nestedRef: ref({ n: ref(0) }),
+  }
+
+  const a = ref(obj)
+  expectType<number>(a.value.n)
+  expectType<number>(a.value.ref)
+  expectType<number>(a.value.nestedRef.n)
+
+  const b = reactive({ a })
+  expectType<number>(b.a.n)
+  expectType<number>(b.a.ref)
+  expectType<number>(b.a.nestedRef.n)
+})
+
 // computed
 describe('allow computed getter and setter types to be unrelated', () => {
   const obj = ref({

+ 5 - 3
packages/reactivity/src/ref.ts

@@ -62,7 +62,9 @@ export function ref(value?: unknown) {
 
 declare const ShallowRefMarker: unique symbol
 
-export type ShallowRef<T = any> = Ref<T> & { [ShallowRefMarker]?: true }
+export type ShallowRef<T = any, S = T> = Ref<T, S> & {
+  [ShallowRefMarker]?: true
+}
 
 /**
  * Shallow version of {@link ref()}.
@@ -490,9 +492,9 @@ export type ShallowUnwrapRef<T> = {
 type DistributeRef<T> = T extends Ref<infer V> ? V : T
 
 export type UnwrapRef<T> =
-  T extends ShallowRef<infer V>
+  T extends ShallowRef<infer V, infer _>
     ? V
-    : T extends Ref<infer V>
+    : T extends Ref<infer V, infer _>
       ? UnwrapRefSimple<V>
       : UnwrapRefSimple<T>