Skip to content

Commit 8e20375

Browse files
committed
fix(types): ensure correct type for toRef and toRefs on existing refs
1 parent 9c23ddf commit 8e20375

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

packages/reactivity/src/ref.ts

+4-5
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ export interface Ref<T = any> {
2020
_shallow?: boolean
2121
}
2222

23-
export type ToRefs<T = any> = { [K in keyof T]: Ref<T[K]> }
23+
export type ToRef<T> = T extends Ref ? T : Ref<UnwrapRef<T>>
24+
export type ToRefs<T = any> = { [K in keyof T]: ToRef<T[K]> }
2425

2526
const convert = <T extends unknown>(val: T): T =>
2627
isObject(val) ? reactive(val) : val
@@ -30,9 +31,7 @@ export function isRef(r: any): r is Ref {
3031
return Boolean(r && r.__v_isRef === true)
3132
}
3233

33-
export function ref<T extends object>(
34-
value: T
35-
): T extends Ref ? T : Ref<UnwrapRef<T>>
34+
export function ref<T extends object>(value: T): ToRef<T>
3635
export function ref<T>(value: T): Ref<UnwrapRef<T>>
3736
export function ref<T = any>(): Ref<T | undefined>
3837
export function ref(value?: unknown) {
@@ -171,7 +170,7 @@ class ObjectRefImpl<T extends object, K extends keyof T> {
171170
export function toRef<T extends object, K extends keyof T>(
172171
object: T,
173172
key: K
174-
): Ref<T[K]> {
173+
): ToRef<T[K]> {
175174
return isRef(object[key])
176175
? object[key]
177176
: (new ObjectRefImpl(object, key) as any)

test-dts/ref.test-d.ts

+18-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ import {
66
unref,
77
reactive,
88
expectType,
9-
proxyRefs
9+
proxyRefs,
10+
toRef,
11+
toRefs
1012
} from './index'
1113

1214
function plainType(arg: number | Ref<number>) {
@@ -154,3 +156,18 @@ const r2 = {
154156
const p2 = proxyRefs(r2)
155157
expectType<number>(p2.a)
156158
expectType<Ref<string>>(p2.obj.k)
159+
160+
// toRef
161+
const obj = {
162+
a: 1,
163+
b: ref(1)
164+
}
165+
expectType<Ref<number>>(toRef(obj, 'a'))
166+
expectType<Ref<number>>(toRef(obj, 'b'))
167+
168+
// toRefs
169+
const objRefs = toRefs(obj)
170+
expectType<{
171+
a: Ref<number>
172+
b: Ref<number>
173+
}>(objRefs)

0 commit comments

Comments
 (0)