繁体   English   中英

vue watch TypeScript 错误TS2769: No overload matches this call

[英]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:没有与此调用匹配的过载。
重载 1 of 3, '(source: SimpleEffect, options?: Pick, "deep" | "flush"> | undefined): StopHandle',出现以下错误。 “$q.screen.width”类型的参数不可分配给“SimpleEffect”类型的参数。

重载 2 of 3,'(来源:WatcherSource,cb:WatcherCallBack,选项?部分|未定义):StopHandle',出现以下错误。 “$q.screen.width”类型的参数不可分配给“WatcherSource”类型的参数。

重载 3 of 3, '(sources: WatcherSource[], cb: (newValues: unknown[], oldValues: unknown[], onCleanup: CleanupRegistrator) => any, options?: Partial | undefined: StopHandle',给出了以下内容错误。 “$q.screen.width”类型的参数不可分配给“WatcherSource[]”类型的参数。

这是针对以下代码行:

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

就目前而言,我将一个string交给watch function 而不是WatcherSource<any> 我尝试了以下但他们都失败了:

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

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

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

下面watchWatcherSource的定义

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))

我在使用 Quasar 时遇到过这个问题,结果是 VS Code 以某种方式自动导入了错误的“手表” object,如下所示:

import { watch } from 'fs';

代替

import { watch } from 'vue';

这就是为什么它期待错误的类型参数。

提醒一下,以防其他人遇到同样的问题。

干杯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM