关于 Svelte 使用 typescript 的反应式语句的问题

问题描述 投票:0回答:2

我在这段代码中遇到了

TS2695
错误。

<script lang="ts">
  let count = 0;
  
  $: count, (() => {
    console.log(`TEST: ${count}`);
  })();
</script>

错误如下。

逗号运算符的左侧未使用,没有副作用。 ts(2695)

我以为逗号运算符的左侧是

count
变量,它是由 console.log() 使用的。

所以,我不知道如何处理这个错误。不过,代码运行良好。

请帮助我如何修复此错误。

typescript svelte
2个回答
2
投票

不,

console.log
没有使用它。 Svelte 中的响应式语句是一段代码,每当其中的任何内容发生变化时都会执行该代码。 Svelte 会在编译时为您查找依赖项。

您想要执行的操作的正确语法是

$: console.log(`TEST: ${count}`);

$: {
  console.log(`TEST: ${count}`);
}

在两者上,console.log 都是通过传递给它的

count
来调用的,因此 Svelte 能够将其推断为依赖项,您不需要指定它。


0
投票

当变量为

let
时,他们似乎已经解决了这个问题,如您的示例所示。但这对于
const
来说仍然是一个问题。以下是一些具有不同优点的替代方案。

解决方法

0。使用
writable

const someVariable = writable(...);

$: $someVariable, processStuff();

这可能是最好的解决方法。不幸的是,在不需要的时候不得不使用商店,但至少这感觉像适当的 Svelte。

1. @ts-预期错误

// @ts-expect-error
$: someVariable, processStuff();

随处使用

@ts-expect-error
(或
@ts-ignore
)并不比随处使用波形曲线更好,并且隐藏了 真正的错误。

2.强制“使用”变量的辅助函数

function depend(..._args: unknown[]) {
  // do nothing
}

$: depend(someVariable), processStuff();

这是足够合理的,尽管额外的函数调用会造成视觉干扰。这是我第二喜欢的方法。

3.使用依赖项数组

$: [someVariable] && processStuff();

我以前见过这个提议,但它只是将一个错误替换为另一个错误。

&&
的左侧始终为真,因此 TS 认为这是不必要的,并且可能会抱怨。

4.确保变量不是 const

let myConstantArray = [];          // Effectively a const, but don't tell TS
myConstantArray = myConstantArray; // An assignment is needed to avoid the warning "use const instead of let"

$: myConstantArray, processStuff();

警告不会出现在

let
上,只出现在
const
上,所以我们可以做一些诡计。但是,哎呀,这是野蛮且容易出错的,因为变量现在可能会被重新分配,而我们真正希望它是
const

5.制作一个模拟依赖关系的包装函数

function thisFunctionIgnoresItsArgumentsAndJustCallsProcessStuff(..._args) {
  processStuff();
}

$: thisFunctionIgnoresItsArgumentsAndJustCallsProcessStuff(someVariable);

这是可能的(希望有一个更好的名字),但它确实会用额外的函数来填充代码。不太好。

6.反应式地声明函数

const someVariable;
const anotherVariable;

$: processStuff = () => {
  ...
  analyze(anotherVariable);  // oops, a change in anotherVariable now triggers the function
}

这是一种危险的做法。这使得很难判断什么条件真正触发该功能。该函数可能不包含应该触发它的变量,相反可能包含其他不应触发它的变量。

© www.soinside.com 2019 - 2024. All rights reserved.