Skip to content

Svelte incorrectly interprets values using Symbol.toPrimitive as static #14854

@Ocean-OS

Description

@Ocean-OS

Describe the bug

If a value in Svelte uses Symbol.toPrimitive for reactivity, Svelte doesn't see this in compilation and interprets the value as static. Here's an example:

<script>
let count = $state(0);
let counter = () => count;
counter[Symbol.toPrimitive] = () => count;
</script>
<button onclick={()=>count++}>Count is {counter}</button>

In this example, counter uses Symbol.toPrimitive in an (admittedly dumb) attempt to add some reactivity without requiring a (visible) function call.
However, the code that interpolates counter compiles to:

button.textContent = `Count is ${counter ?? ""}`;

...which is a static statement with no reactivity.
While I have found that wrapping the value in $state like so...

/*... insert stuff from example... */
let reactiveCounter = $state(counter);
/* replace `Count is {counter}` with `Count is {reactiveCounter}`... */

...makes everything work, this feels like more work than necessary, since count is still a "dependency" of counter (and in turn reactiveCounter).
This is an edge case, but it would be useful if these values could be correctly interpreted as reactive by the compiler.

Reproduction

REPL

Logs

No response

System Info

N/A

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions