]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
fix(types): improve ref typing, close #759
authorEvan You <yyx990803@gmail.com>
Fri, 21 Feb 2020 16:45:42 +0000 (17:45 +0100)
committerEvan You <yyx990803@gmail.com>
Fri, 21 Feb 2020 16:45:42 +0000 (17:45 +0100)
packages/reactivity/src/ref.ts
test-dts/ref.test-d.ts [new file with mode: 0644]

index 65e1b8dd01655f8aa905627837a07ebc6b4dadda..b36b3308b3946d7805426da06ac31cf3898b65b0 100644 (file)
@@ -23,12 +23,12 @@ export interface Ref<T = any> {
 const convert = <T extends unknown>(val: T): T =>
   isObject(val) ? reactive(val) : val
 
-export function isRef<T>(r: Ref<T> | T): r is Ref<T>
+export function isRef<T>(r: Ref<T> | unknown): r is Ref<T>
 export function isRef(r: any): r is Ref {
   return r ? r._isRef === true : false
 }
 
-export function ref<T extends Ref>(value: T): T
+export function ref<T>(value: T): T extends Ref ? T : Ref<T>
 export function ref<T>(value: T): Ref<T>
 export function ref<T = any>(): Ref<T>
 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 (file)
index 0000000..ad8c22f
--- /dev/null
@@ -0,0 +1,16 @@
+import { expectType } from 'tsd'
+import { Ref, ref } from './index'
+import { isRef } from '@vue/reactivity'
+
+function foo(arg: number | Ref<number>) {
+  // ref coercing
+  const coerced = ref(arg)
+  expectType<Ref<number>>(coerced)
+
+  // isRef as type guard
+  if (isRef(arg)) {
+    expectType<Ref<number>>(arg)
+  }
+}
+
+foo(1)