From 925bc346fe85091467fcd2e40d6c1ff07f3b51c4 Mon Sep 17 00:00:00 2001 From: Che Guevara <836934184@qq.com> Date: Fri, 8 Oct 2021 23:57:49 +0800 Subject: [PATCH] fix(types): make `toRef` return correct type(fix #4732) (#4734) * fix(types): make `toRef` return correct type(fix #4732) * chore: use correct test Co-authored-by: Evan You --- packages/reactivity/src/ref.ts | 6 ++++-- test-dts/ref.test-d.ts | 13 +++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/reactivity/src/ref.ts b/packages/reactivity/src/ref.ts index a4a69b1f..f3337582 100644 --- a/packages/reactivity/src/ref.ts +++ b/packages/reactivity/src/ref.ts @@ -65,7 +65,9 @@ export function isRef(r: any): r is Ref { return Boolean(r && r.__v_isRef === true) } -export function ref(value: T): ToRef +export function ref( + value: T +): [T] extends [Ref] ? T : Ref> export function ref(value: T): Ref> export function ref(): Ref export function ref(value?: unknown) { @@ -212,7 +214,7 @@ class ObjectRefImpl { } } -export type ToRef = [T] extends [Ref] ? T : Ref> +export type ToRef = [T] extends [Ref] ? T : Ref export function toRef( object: T, key: K diff --git a/test-dts/ref.test-d.ts b/test-dts/ref.test-d.ts index c7f12837..8129d618 100644 --- a/test-dts/ref.test-d.ts +++ b/test-dts/ref.test-d.ts @@ -10,6 +10,7 @@ import { toRef, toRefs, ToRefs, + shallowReactive, watch } from './index' @@ -236,3 +237,15 @@ function testUnrefGenerics(p: T | Ref) { } testUnrefGenerics(1) + +// #4732 +const baz = shallowReactive({ + foo: { + bar: ref(42) + } +}) + +const foo = toRef(baz, 'foo') + +expectType>(foo.value.bar) +expectType(foo.value.bar.value)