Skip to content

Svelte 5 runes documentation -- add more explanation about having to use classes rather than pojos for "composite" state #9971

Closed
@cdcarson

Description

@cdcarson

Describe the problem

Sorry about the goofy issue title. What I mean is this:

// src/lib/api.svelte.ts

export type Example = {
  value: number;
  doubled: number;
}

// Doesn't work! (returns a pojo)
export const getExampleRunes = (initialValue: number): Example => {
  const value = $state(initialValue);
  const doubled = $derived(value * 2);
  return {value, doubled}
}

// Works!
export class ExampleRunes implements Example {
  value = $state(0);
  doubled = $derived(this.value * 2)
  constructor(initialValue: number) {
    this.value = initialValue;
  }
}

Context: I was converting a function that created a hash of Svelte stores to runes, and missed the implication of the note on the docs page that says:

In this example, the compiler transforms done and text into get/set methods on the class prototype referencing private fields

So I spent a while wondering why the pojo returned from getExampleRunes above wasn't working.

Describe the proposed solution

Consider adding another sentence to that note, something like...

Important: You must define a class for this to work. Svelte can't do this for plain javascript objects.

Alternatives considered

I'm fine with using classes. It's just a documentation issue.

Importance

nice to have

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