考虑以下代码:
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
解决这个问题的正确方法是什么?