Question about Svelte's reactive statements with typescript

Viewed 262

I got the TS2695 error in this code.

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

The error was the below.

Left side of comma operator is unused and has no side effects. ts(2695)

I thought the left side of the comma operator is the count variable, and it is used by console.log().

So, I didn't know how to handle this error. However, the code works well.

Please help me how to fix this error.

1 Answers

No, it's not used by console.log. A reactive statement in Svelte is a piece of code that executes everytime anything inside it changes. Svelte take care of finding the dependencies at compile time for you.

The proper syntax for what you're trying to do is

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

or

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

On both, console.log is invoked with count passed to it, so Svelte is able to infer it as a dependency, you don't need to specify it.

Related