Skip to content

Commit 925bc34

Browse files
fix(types): make toRef return correct type(fix vuejs#4732) (vuejs#4734)
* fix(types): make `toRef` return correct type(fix vuejs#4732) * chore: use correct test Co-authored-by: Evan You <yyx990803@gmail.com>
1 parent f66d456 commit 925bc34

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

packages/reactivity/src/ref.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,9 @@ export function isRef(r: any): r is Ref {
6565
return Boolean(r && r.__v_isRef === true)
6666
}
6767

68-
export function ref<T extends object>(value: T): ToRef<T>
68+
export function ref<T extends object>(
69+
value: T
70+
): [T] extends [Ref] ? T : Ref<UnwrapRef<T>>
6971
export function ref<T>(value: T): Ref<UnwrapRef<T>>
7072
export function ref<T = any>(): Ref<T | undefined>
7173
export function ref(value?: unknown) {
@@ -212,7 +214,7 @@ class ObjectRefImpl<T extends object, K extends keyof T> {
212214
}
213215
}
214216

215-
export type ToRef<T> = [T] extends [Ref] ? T : Ref<UnwrapRef<T>>
217+
export type ToRef<T> = [T] extends [Ref] ? T : Ref<T>
216218
export function toRef<T extends object, K extends keyof T>(
217219
object: T,
218220
key: K

test-dts/ref.test-d.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
toRef,
1111
toRefs,
1212
ToRefs,
13+
shallowReactive,
1314
watch
1415
} from './index'
1516

@@ -236,3 +237,15 @@ function testUnrefGenerics<T>(p: T | Ref<T>) {
236237
}
237238

238239
testUnrefGenerics(1)
240+
241+
// #4732
242+
const baz = shallowReactive({
243+
foo: {
244+
bar: ref(42)
245+
}
246+
})
247+
248+
const foo = toRef(baz, 'foo')
249+
250+
expectType<Ref<number>>(foo.value.bar)
251+
expectType<number>(foo.value.bar.value)

0 commit comments

Comments
 (0)