【问题标题】:Vue watch TypeScript error TS2769: No overload matches this callVue watch TypeScript错误TS2769:没有重载匹配这个调用
【发布时间】:2020-08-22 19:23:06
【问题描述】:

考虑以下代码:

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, '(来源: SimpleEffect, options?: Pick, "deep" | “冲洗”> | undefined): StopHandle',给出以下错误。 '"$q.screen.width"' 类型的参数不能分配给 'SimpleEffect' 类型的参数。

Overload 2 of 3, '(source: WatcherSource, cb: WatcherCallBack, options?Partial | undefined): 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 函数而不是WatcherSource<any>。我尝试了以下方法,但都失败了:

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

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

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

【问题讨论】:

    标签: javascript typescript vue.js vue-component vue-composition-api


    【解决方案1】:

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

    【讨论】:

    • 嗯...如果我使用您的建议 TS 抱怨它找不到 $q 并且当我在它周围加上引号作为字符串时没有 TS 错误但不会触发手表回调
    • Quasar docs 中所述,由import { Screen } from 'quasar' 修复该部分,然后像watch(() =&gt; Screen.width, (width) =&gt; setMiniState(true, +width)) 一样使用它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 2020-06-14
    • 2021-12-19
    相关资源
    最近更新 更多