diff --git a/packages/reactivity/src/ref.ts b/packages/reactivity/src/ref.ts index 04464fdf..e3633f98 100644 --- a/packages/reactivity/src/ref.ts +++ b/packages/reactivity/src/ref.ts @@ -20,7 +20,8 @@ export interface Ref { _shallow?: boolean } -export type ToRefs = { [K in keyof T]: Ref } +export type ToRef = T extends Ref ? T : Ref> +export type ToRefs = { [K in keyof T]: ToRef } const convert = (val: T): T => isObject(val) ? reactive(val) : val @@ -30,9 +31,7 @@ export function isRef(r: any): r is Ref { return Boolean(r && r.__v_isRef === true) } -export function ref( - value: T -): T extends Ref ? T : Ref> +export function ref(value: T): ToRef export function ref(value: T): Ref> export function ref(): Ref export function ref(value?: unknown) { @@ -171,7 +170,7 @@ class ObjectRefImpl { export function toRef( object: T, key: K -): Ref { +): ToRef { return isRef(object[key]) ? object[key] : (new ObjectRefImpl(object, key) as any) diff --git a/test-dts/ref.test-d.ts b/test-dts/ref.test-d.ts index c961f4be..f736977b 100644 --- a/test-dts/ref.test-d.ts +++ b/test-dts/ref.test-d.ts @@ -6,7 +6,9 @@ import { unref, reactive, expectType, - proxyRefs + proxyRefs, + toRef, + toRefs } from './index' function plainType(arg: number | Ref) { @@ -154,3 +156,18 @@ const r2 = { 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')) + +// toRefs +const objRefs = toRefs(obj) +expectType<{ + a: Ref + b: Ref +}>(objRefs)