Skip to content

Commit

Permalink
fix(types): ensure correct type for toRef and toRefs on existing refs
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Oct 27, 2020
1 parent 9c23ddf commit 8e20375
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
9 changes: 4 additions & 5 deletions packages/reactivity/src/ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ export interface Ref<T = any> {
_shallow?: boolean
}

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

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

export function ref<T extends object>(
value: T
): T extends Ref ? T : Ref<UnwrapRef<T>>
export function ref<T extends object>(value: T): ToRef<T>
export function ref<T>(value: T): Ref<UnwrapRef<T>>
export function ref<T = any>(): Ref<T | undefined>
export function ref(value?: unknown) {
Expand Down Expand Up @@ -171,7 +170,7 @@ class ObjectRefImpl<T extends object, K extends keyof T> {
export function toRef<T extends object, K extends keyof T>(
object: T,
key: K
): Ref<T[K]> {
): ToRef<T[K]> {
return isRef(object[key])
? object[key]
: (new ObjectRefImpl(object, key) as any)
Expand Down
19 changes: 18 additions & 1 deletion test-dts/ref.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import {
unref,
reactive,
expectType,
proxyRefs
proxyRefs,
toRef,
toRefs
} from './index'

function plainType(arg: number | Ref<number>) {
Expand Down Expand Up @@ -154,3 +156,18 @@ const r2 = {
const p2 = proxyRefs(r2)
expectType<number>(p2.a)
expectType<Ref<string>>(p2.obj.k)

// toRef
const obj = {
a: 1,
b: ref(1)
}
expectType<Ref<number>>(toRef(obj, 'a'))
expectType<Ref<number>>(toRef(obj, 'b'))

// toRefs
const objRefs = toRefs(obj)
expectType<{
a: Ref<number>
b: Ref<number>
}>(objRefs)

0 comments on commit 8e20375

Please sign in to comment.