From: Evan You Date: Fri, 21 Feb 2020 16:45:42 +0000 (+0100) Subject: fix(types): improve ref typing, close #759 X-Git-Tag: v3.0.0-alpha.6~7 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=627b9df4a293ae18071009d9cac7a5e995d40716;p=thirdparty%2Fvuejs%2Fcore.git fix(types): improve ref typing, close #759 --- diff --git a/packages/reactivity/src/ref.ts b/packages/reactivity/src/ref.ts index 65e1b8dd01..b36b3308b3 100644 --- a/packages/reactivity/src/ref.ts +++ b/packages/reactivity/src/ref.ts @@ -23,12 +23,12 @@ export interface Ref { const convert = (val: T): T => isObject(val) ? reactive(val) : val -export function isRef(r: Ref | T): r is Ref +export function isRef(r: Ref | unknown): r is Ref export function isRef(r: any): r is Ref { return r ? r._isRef === true : false } -export function ref(value: T): T +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) { diff --git a/test-dts/ref.test-d.ts b/test-dts/ref.test-d.ts new file mode 100644 index 0000000000..ad8c22fef6 --- /dev/null +++ b/test-dts/ref.test-d.ts @@ -0,0 +1,16 @@ +import { expectType } from 'tsd' +import { Ref, ref } from './index' +import { isRef } from '@vue/reactivity' + +function foo(arg: number | Ref) { + // ref coercing + const coerced = ref(arg) + expectType>(coerced) + + // isRef as type guard + if (isRef(arg)) { + expectType>(arg) + } +} + +foo(1)