From 27f4678d9d631c009d2fc0388944f9d57edf9f59 Mon Sep 17 00:00:00 2001 From: pikax Date: Wed, 6 May 2020 08:31:18 +0100 Subject: [PATCH] types: allow using ref with unknown generic types --- packages/reactivity/src/ref.ts | 15 ++++++++++++++- test-dts/ref.test-d.ts | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/packages/reactivity/src/ref.ts b/packages/reactivity/src/ref.ts index d22e6a0e969..e18274af6bd 100644 --- a/packages/reactivity/src/ref.ts +++ b/packages/reactivity/src/ref.ts @@ -27,10 +27,23 @@ export function isRef(r: any): r is Ref { return r ? r.__v_isRef === true : false } +// explicit `boolean` otherwise it will return +// `Ref | Ref` instead of `Ref` +export function ref(value: boolean): Ref +// handles normal object export function ref( value: T ): T extends Ref ? T : Ref> -export function ref(value: T): Ref> + +// handles ref object +export function ref(value: T): T + +// handles unknown and some odd types +export function ref( + value: T +): T extends Ref ? T : Ref> + +// export function ref(value: T): Ref> export function ref(): Ref export function ref(value?: unknown) { return createRef(value) diff --git a/test-dts/ref.test-d.ts b/test-dts/ref.test-d.ts index e2454e035c8..34064029d32 100644 --- a/test-dts/ref.test-d.ts +++ b/test-dts/ref.test-d.ts @@ -85,6 +85,39 @@ function withSymbol() { withSymbol() +function generics() { + ;(function unknownGeneric(v: T) { + const r = ref(v) + expectType(r.value) // T in this case can be anything + }) + ;(function stringGeneric(v: T) { + const r = ref(v) + expectType(r.value) + }) + ;(function assignedGeneric(v: T) { + const r = ref(v) + expectType(r.value) // T in this case can be anything + }) + ;(function extendsGeneric(v: T) { + const r = ref(v) + expectType<{ a: 1 }>(r.value) // this will infer the actual type instead of being generic + }) + ;(function functionGeneric number>(v: T) { + const r = ref(v) + expectType<(a: number, b: string) => number>(r.value) // this will infer the actual type instead of being generic + }) + ;(function arrayGeneric>(v: T) { + const r = ref(v) + expectType>(r.value) + }) + ;(function tupleGeneric(v: T) { + const r = ref(v) + expectType<[number, string]>(r.value) + }) +} + +generics() + const state = reactive({ foo: { value: 1,