0

考虑以下代码:

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”|“flush”>|undefined):StopHandle',给出了以下错误。'"$q.screen.width"' 类型的参数不能分配给 'SimpleEffect' 类型的参数。

重载 2 of 3, '(source: WatcherSource, cb: WatcherCallBack, options?Partial | undefined): StopHandle', 给出了以下错误。'"$q.screen.width"' 类型的参数不能分配给 'WatcherSource' 类型的参数。

重载 3 之 3,'(来源:WatcherSource[],cb:(newValues:unknown[],oldValues:unknown[],onCleanup:CleanupRegistrator)=> any,options?:部分|未定义):StopHandle',给出以下错误。'"$q.screen.width"' 类型的参数不能分配给 'WatcherSource[]' 类型的参数。

这是针对以下代码行:

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

就目前而言,我将 astring交给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

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

4

1 回答 1

3

这是和的定义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))
于 2020-05-07T13:40:35.830 回答