javascript - 多个 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.
有谁知道可能的解决方案?从本质上讲,这些错误正在停止重新加载我的开发服务器......而且它正在成为一个令人沮丧的开发瓶颈......
解决方案
我找不到函数的类型定义,你也没有提供一个工作示例,所以我只能猜测:
错误说 , newX
, newY
,prevX
有prevY
类型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
推荐阅读
- winapi - 如何只安装 mt.exe?
- rest - 使用 REST 返回一个值
- reactjs - nextjs中“页面”内的CSS
- c++ - 如何在类中分配多维数组?当行>列时会引发错误?
- javascript - Node js 使用 mocha chai 测试受保护的路由?
- wso2 - 是否可以使用 wso2 Identity Server 获取非 oauth2 令牌并将其与 wso2 APIManager 一起使用?
- php - 如何获取指定了所有关系数据的数据
- spring-boot - 在 docker-compose 上为 Spring Boot 应用程序发送应用程序参数?
- python - 如何从 Pandas 合并打印错误类型?
- python - 如何在文本行中替换这些值