svelte: Svelte 5 Exporting $state compile problem

Describe the bug

If I want to export a shared state, the normal way is to do like this:

Option 1

// rune.svelte.ts

export const rune = <T>(initialValue: T) => {

    let _rune = $state(initialValue);

    return {
        get value() {
            return _rune;
        },
        set value(v: T) {
            _rune = v;
        }
    };
};

Option 2

This also works:

// rune.svelte.ts

export const rune = <T>(initialValue: T) => {
    const _rune = $state({ value: initialValue });
    return _rune;
};

Option 3

However, if I simplify option 2, I get a compile error:

export const rune = <T>(initialValue: T) => $state({ value: initialValue });

// OR

export const rune = <T>(initialValue: T) => {
  return $state({ value: initialValue });
};

I get the error:

$state(...)` can only be used as a variable declaration initializer or a class field

I would expect Option 3 to compile the exact same way as option 2 !?

Reproduction

REPL

Logs

Error message above.

System Info

Svelte 5.2.0

Severity

annoyance

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Comments: 17 (15 by maintainers)

Most upvoted comments

What we could do is permit return $state() but add a runtime check in DEV that checks if the object is actually a proxy and throw an error/warning if not the case.