Skip to content

Commit

Permalink
types(runtime-core): add OnCleanup parameter type in this.$watch (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
Alfred-Skyblue authored May 27, 2024
1 parent c6a4c08 commit 521988d
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 5 deletions.
8 changes: 6 additions & 2 deletions packages/dts-test/watch.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -92,9 +95,10 @@ defineComponent({
created() {
this.$watch(
() => this.a,
(v, ov) => {
(v, ov, onCleanup) => {
expectType<number>(v)
expectType<number>(ov)
expectType<OnCleanup>(onCleanup)
},
)
},
Expand Down
2 changes: 1 addition & 1 deletion packages/runtime-core/src/apiWatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
5 changes: 3 additions & 2 deletions packages/runtime-core/src/componentPublicInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
} from './component'
import { nextTick, queueJob } from './scheduler'
import {
type OnCleanup,
type WatchOptions,
type WatchStopHandle,
instanceWatch,
Expand Down Expand Up @@ -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>>> &
Expand Down

0 comments on commit 521988d

Please sign in to comment.