Vue 观察 TypeScript 错误 TS2769:没有重载匹配此调用

Vue watch TypeScript error TS2769: No overload matches this call

考虑以下代码:

export default defineComponent({
  setup() {
    const miniState = ref(true)

    const setMiniState = (state: boolean, screenWidth: number) => {
      if (screenWidth > 1023) {
        miniState.value = false
      } else if (state !== void 0) {
        miniState.value = state === true
      }
      else {
        miniState.value = true
      }
    }

    watch('$q.screen.width', (width) => setMiniState(true, width))

    return { miniState, setMiniState }
  }
})

TypeScript 抛出此错误:

TS2769: No overload matches this call.
Overload 1 of 3, '(source: SimpleEffect, options?: Pick, "deep" | "flush"> | undefined): StopHandle', gave the following error. Argument of type '"$q.screen.width"' is not assignable to parameter of type 'SimpleEffect'.

Overload 2 of 3, '(source: WatcherSource, cb: WatcherCallBack, options? Partial | undefined): StopHandle', gave the following error. Argument of type '"$q.screen.width"' is not assignable to parameter of type 'WatcherSource'.

Overload 3 of 3, '(sources: WatcherSource[], cb: (newValues: unknown[], oldValues: unknown[], onCleanup: CleanupRegistrator) => any, options?: Partial | undefined): StopHandle', gave the following error. Argument of type '"$q.screen.width"' is not assignable to parameter of type 'WatcherSource[]'.

这是针对以下代码行:

watch('$q.screen.width', (width) => setMiniState(true, width))

目前我将 string 移交给 watch 函数而不是 WatcherSource<any>。我尝试了以下但都失败了:

watch('$q.screen.width' as WatcherSource, (width) => setMiniState(true, width)) // fails

watch(('$q.screen.width' as WatcherSource ), (width) => setMiniState(true, width)) // fails

解决这个问题的正确方法是什么?

这是definition of watch and WatcherSource

function watch<T>(
  source: WatcherSource<T>,
  callback: (
    value: T,
    oldValue: T,
    onInvalidate: InvalidateCbRegistrator
  ) => void,
  options?: WatchOptions
): StopHandle

type WatcherSource<T> = Ref<T> | (() => T)

据此,您应该传递 ref 或回调。

watch(() => $q.screen.width, (width) => setMiniState(true, width))