簡體   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