From c6cd6a7938b6ba74a018d552e2f3191e307870c2 Mon Sep 17 00:00:00 2001 From: JensDll Date: Thu, 25 Nov 2021 10:39:09 +0100 Subject: [PATCH] fix (types): do not unwrap refs in `toRefs` (#4966) --- packages/reactivity/src/ref.ts | 4 +- test-dts/ref.test-d.ts | 72 +++++++++++++++++----------------- 2 files changed, 38 insertions(+), 38 deletions(-) diff --git a/packages/reactivity/src/ref.ts b/packages/reactivity/src/ref.ts index fb43668e455..93eb4fa89b0 100644 --- a/packages/reactivity/src/ref.ts +++ b/packages/reactivity/src/ref.ts @@ -190,9 +190,7 @@ export function customRef(factory: CustomRefFactory): Ref { } export type ToRefs = { - // #2687: somehow using ToRef here turns the resulting type into - // a union of multiple Ref<*> types instead of a single Ref<* | *> type. - [K in keyof T]: T[K] extends Ref ? T[K] : Ref> + [K in keyof T]: ToRef } export function toRefs(object: T): ToRefs { if (__DEV__ && !isProxy(object)) { diff --git a/test-dts/ref.test-d.ts b/test-dts/ref.test-d.ts index d4462db9e39..5b5274c9881 100644 --- a/test-dts/ref.test-d.ts +++ b/test-dts/ref.test-d.ts @@ -10,8 +10,7 @@ import { toRef, toRefs, ToRefs, - shallowReactive, - watch + shallowReactive } from './index' function plainType(arg: number | Ref) { @@ -185,28 +184,45 @@ const p2 = proxyRefs(r2) expectType(p2.a) expectType>(p2.obj.k) -// toRef -const obj = { - a: 1, - b: ref(1) -} -expectType>(toRef(obj, 'a')) -expectType>(toRef(obj, 'b')) +// toRef and toRefs +{ + const obj: { + a: number + b: Ref + c: number | string + } = { + a: 1, + b: ref(1), + c: 1 + } -const objWithUnionProp: { a: string | number } = { - a: 1 -} + // toRef + expectType>(toRef(obj, 'a')) + expectType>(toRef(obj, 'b')) + // Should not distribute Refs over union + expectType>(toRef(obj, 'c')) + + // toRefs + expectType<{ + a: Ref + b: Ref + // Should not distribute Refs over union + c: Ref + }>(toRefs(obj)) + + // Both should not do any unwrapping + const someReactive = shallowReactive({ + a: { + b: ref(42) + } + }) -watch(toRef(objWithUnionProp, 'a'), value => { - expectType(value) -}) + const toRefResult = toRef(someReactive, 'a') + const toRefsResult = toRefs(someReactive) -// toRefs -const objRefs = toRefs(obj) -expectType<{ - a: Ref - b: Ref -}>(objRefs) + expectType>(toRefResult.value.b) + expectType>(toRefsResult.a.value.b) +} // #2687 interface AppData { @@ -238,20 +254,6 @@ function testUnrefGenerics(p: T | Ref) { testUnrefGenerics(1) -// #4732 -describe('ref in shallow reactive', () => { - const baz = shallowReactive({ - foo: { - bar: ref(42) - } - }) - - const foo = toRef(baz, 'foo') - - expectType>(foo.value.bar) - expectType(foo.value.bar.value) -}) - // #4771 describe('shallow reactive in reactive', () => { const baz = reactive({