Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

types(runtime-core): add OnCleanup parameter type in this.$watch #9371

Merged
merged 12 commits into from
May 27, 2024
Merged
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 @@ -5,10 +5,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 @@ -85,9 +88,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 @@ -66,7 +66,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
11 changes: 8 additions & 3 deletions packages/runtime-core/src/componentPublicInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ import {
isStatefulComponent
} from './component'
import { nextTick, queueJob } from './scheduler'
import { instanceWatch, WatchOptions, WatchStopHandle } from './apiWatch'
import {
instanceWatch,
OnCleanup,
WatchOptions,
WatchStopHandle
} from './apiWatch'
import {
EMPTY_OBJ,
hasOwn,
Expand Down Expand Up @@ -222,8 +227,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