]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
types(runtime-core): add `OnCleanup` parameter type in `this.$watch` (#9371)
author远方os <yangpanteng@gmail.com>
Mon, 27 May 2024 16:25:07 +0000 (00:25 +0800)
committerGitHub <noreply@github.com>
Mon, 27 May 2024 16:25:07 +0000 (00:25 +0800)
packages/dts-test/watch.test-d.ts
packages/runtime-core/src/apiWatch.ts
packages/runtime-core/src/componentPublicInstance.ts

index 5986d3d30b182fb3bab939341d809f4a9d26f6c8..507fb6f5dcd9317bfa276699f8511544731f9b8f 100644 (file)
@@ -12,10 +12,13 @@ const source = ref('foo')
 const source2 = computed(() => source.value)
 const source3 = () => 1
 
+type OnCleanup = (fn: () => void) => void
+
 // lazy watcher will have consistent types for oldValue.
-watch(source, (value, oldValue) => {
+watch(source, (value, oldValue, onCleanup) => {
   expectType<string>(value)
   expectType<string>(oldValue)
+  expectType<OnCleanup>(onCleanup)
 })
 
 watch([source, source2, source3], (values, oldValues) => {
@@ -92,9 +95,10 @@ defineComponent({
   created() {
     this.$watch(
       () => this.a,
-      (v, ov) => {
+      (v, ov, onCleanup) => {
         expectType<number>(v)
         expectType<number>(ov)
+        expectType<OnCleanup>(onCleanup)
       },
     )
   },
index 0fd6b050cfa02f96b6cde34ffadc6efadab31578..ffad8ad549583e5c60aea4caba48b2c7266339f1 100644 (file)
@@ -65,7 +65,7 @@ type MapSources<T, Immediate> = {
       : never
 }
 
-type OnCleanup = (cleanupFn: () => void) => void
+export type OnCleanup = (cleanupFn: () => void) => void
 
 export interface WatchOptionsBase extends DebuggerOptions {
   flush?: 'pre' | 'post' | 'sync'
index 357ad280b9bf647c074ac3ca8b7bc83f66e2b146..52801e172ab266f1d93f8df2bbee4cbd21350813 100644 (file)
@@ -6,6 +6,7 @@ import {
 } from './component'
 import { nextTick, queueJob } from './scheduler'
 import {
+  type OnCleanup,
   type WatchOptions,
   type WatchStopHandle,
   instanceWatch,
@@ -229,8 +230,8 @@ export type ComponentPublicInstance<
   $watch<T extends string | ((...args: any) => any)>(
     source: T,
     cb: T extends (...args: any) => infer R
-      ? (...args: [R, R]) => any
-      : (...args: any) => any,
+      ? (...args: [R, R, OnCleanup]) => any
+      : (...args: [any, any, OnCleanup]) => any,
     options?: WatchOptions,
   ): WatchStopHandle
 } & IfAny<P, P, Omit<P, keyof ShallowUnwrapRef<B>>> &