fix(types): ensure correct type for toRef and toRefs on existing refs

This commit is contained in:
Evan You 2020-10-27 18:50:34 -04:00
parent 9c23ddf9c5
commit 8e20375372
2 changed files with 22 additions and 6 deletions

View File

@ -20,7 +20,8 @@ export interface Ref<T = any> {
_shallow?: boolean _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 => const convert = <T extends unknown>(val: T): T =>
isObject(val) ? reactive(val) : val isObject(val) ? reactive(val) : val
@ -30,9 +31,7 @@ export function isRef(r: any): r is Ref {
return Boolean(r && r.__v_isRef === true) return Boolean(r && r.__v_isRef === true)
} }
export function ref<T extends object>( export function ref<T extends object>(value: T): ToRef<T>
value: T
): T extends Ref ? T : Ref<UnwrapRef<T>>
export function ref<T>(value: T): Ref<UnwrapRef<T>> export function ref<T>(value: T): Ref<UnwrapRef<T>>
export function ref<T = any>(): Ref<T | undefined> export function ref<T = any>(): Ref<T | undefined>
export function ref(value?: unknown) { export function ref(value?: unknown) {
@ -171,7 +170,7 @@ class ObjectRefImpl<T extends object, K extends keyof T> {
export function toRef<T extends object, K extends keyof T>( export function toRef<T extends object, K extends keyof T>(
object: T, object: T,
key: K key: K
): Ref<T[K]> { ): ToRef<T[K]> {
return isRef(object[key]) return isRef(object[key])
? object[key] ? object[key]
: (new ObjectRefImpl(object, key) as any) : (new ObjectRefImpl(object, key) as any)

View File

@ -6,7 +6,9 @@ import {
unref, unref,
reactive, reactive,
expectType, expectType,
proxyRefs proxyRefs,
toRef,
toRefs
} from './index' } from './index'
function plainType(arg: number | Ref<number>) { function plainType(arg: number | Ref<number>) {
@ -154,3 +156,18 @@ const r2 = {
const p2 = proxyRefs(r2) const p2 = proxyRefs(r2)
expectType<number>(p2.a) expectType<number>(p2.a)
expectType<Ref<string>>(p2.obj.k) 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)