Vue观看TypeScript错误TS2769:此调用没有重载

时间:2020-05-07 13:17:00

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

考虑以下代码:

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之3,'(来源: SimpleEffect,选项?:选择“深层” | “冲洗”> |未定义):StopHandle',给出了以下错误。 无法将类型“ $ q.screen.width”的参数分配给类型“ SimpleEffect”的参数。

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

超载3之3,'(源:WatcherSource [],cb :( newValues:不明[],oldValues:不明[],onCleanup:CleanupRegistrator)=>任何,选项?:部分|未定义):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

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

1 个答案:

答案 0 :(得分: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或callback。

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