首页 > 解决方案 > 多个 Vue 3 观察者和 Typescript ......如何使用?

问题描述

注意我正在使用该@vueuse/core库来获取以下示例的一些值,但我相信对于这个问题的库的了解是没有实际意义的。

我有以下三重观察者:

// Reactive Mouse Positionining
const { x, y } = useMouse()

//  Detect if the Mouse has been pressed:
const { pressed } = useMousePressed({ 
  target: celestiaSkyViewerRoot, 
  touch: true 
})

watch([pressed, x, y], ([newPressed, newX, newY], [prevPressed, prevX, prevY]) => {
  if (showConstellations.value) {
    if (!newPressed && newX !== prevX) {
      activeConstellation.value = getActiveConstellation(newX, newY)
    }
  }

  dragging.value = pressed.value

  if (newPressed && newX !== prevX) {
    azimuthalOffset.value -= (newX - prevX) / 6
  }
})

但是,我看到出现以下 Typescript 错误:

对于newX,与线有关:activeConstellation.value = getActiveConstellation(newX, newY)

Argument of type 'number | boolean' is not assignable to parameter of type 'number'. Type 'boolean' is not assignable to type 'number'.

对于newX,与线有关:azimuthalOffset.value -= (newX - prevX) / 6

The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

但是,Vetur 仅显示newY与以下行有关的问题azimuthalOffset.value -= (newX - prevX) / 6

The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

有谁知道可能的解决方案?从本质上讲,这些错误正在停止重新加载我的开发服务器......而且它正在成为一个令人沮丧的开发瓶颈......

标签: javascripttypescriptvuejs3vue-composition-apivetur

解决方案


我找不到函数的类型定义,你也没有提供一个工作示例,所以我只能猜测:

错误说 , newX, newY,prevXprevY类型number | boolean,但我不能告诉你为什么。您的代码编写方式,您希望它们是number唯一的。

三种解决方案的行为都略有不同,但它们都应该使用 typescript 进行编译:

如果任何变量不是,请不要进一步执行number

watch([pressed, x, y], ([newPressed, newX, newY], [prevPressed, prevX, prevY]) => {
  if (typeof newX !== 'number' || typeof newY !== 'number' ||
      typeof prevX !== 'number' || typeof prevY !== 'number') return;
  if (showConstellations.value) {
  ...

如果变量不是类型,则使用默认值number

watch([pressed, x, y], ([newPressed, newX, newY], [prevPressed, prevX, prevY]) => {
  if (typeof newX !== 'number') newX = 0;
  if (typeof newY !== 'number') newY = 0;
  if (typeof prevX !== 'number') prevX = 0;
  if (typeof prevY !== 'number') prevY = 0;
  if (showConstellations.value) {
  ...

强制这些变量为number. 如果这些变量中的任何一个实际上可以是boolean(我不确定),那么在这种情况下,这将导致意外行为:

watch([pressed, x, y], ([newPressed, newX, newY], [prevPressed, prevX, prevY]) => {
  ...
    activeConstellation.value = getActiveConstellation(newX as number, newY as number);
  ...
    azimuthalOffset.value -= ((newX as number) - (prevX as number)) / 6
  

推荐阅读