Skip to content

feat: State declarations in class constructors #15820

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 57 commits into
base: main
Choose a base branch
from

Conversation

elliott-with-the-longest-name-on-github
Copy link
Contributor

There's an annoying problem right now, which comes in about two flavors:

class Counter {
  count = $state<number>();

  constructor(init: number) {
    // oops, forgot to assign init to count, but TypeScript
    // can't help because it thinks it's been assigned above!
  }
}

In this case, TypeScript can't help out because it thinks count has been assigned at its declaration, when it has not!

The other version is:

class PluggableCounter {
  count = $state(0);
  plugin = $state();
  // I shouldn't have to do this
  custom = $derived(this.plugin(this.count));

  constructor(plugin: (c: number) => number) {
    this.plugin = plugin;
  }
}

There are other examples and edge cases ($derived class fields don't play well if you need to reference a non-stateful class field, for example), but the whole class of problem essentially boils down to "sometimes you need to be able to create state in the constructor".

After this PR, you can:

class PluggableCounter {
  count = $state(0);
  custom: number;

  constructor(plugin: (c: number) => number) {
    this.custom = $derived(plugin(this.count));
  }
}

There's a really simple set of rules to follow to declare state in the constructor:

  • The field must not already be declared state
  • In the constructor, the first assignment to the field must be with the rune
  • Creation of the state field can only occur at the top level of the constructor (i.e. not in callbacks or control flow blocks)

Implementation details:

  • Basically all of the analysis stuff we need to do is the same between server and client, except for the actual AST we produce -- so I pulled out all of the duplicate code from those and put it into a shared module.

Before submitting the PR, please make sure you do the following

  • It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs
  • Prefix your PR title with feat:, fix:, chore:, or docs:.
  • This message body should clearly illustrate what problems it solves.
  • Ideally, include a test that fails without this PR but passes with it.
  • If this PR changes code within packages/svelte/src, add a changeset (npx changeset).

Tests and linting

  • Run the tests with pnpm test and lint the project with pnpm lint

Copy link

changeset-bot bot commented Apr 23, 2025

🦋 Changeset detected

Latest commit: 63e60c7

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
svelte Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
Contributor

Playground

pnpm add https://pkg.pr.new/svelte@15820

@svelte-docs-bot
Copy link

@Rich-Harris
Copy link
Member

TODO: re-use the analysis during the transformation phase. Will pick this back up tomorrow

@Rich-Harris
Copy link
Member

By reusing the analysis during the transform phase I was able to simplify things to the tune of several hundred LOC


if (rune && is_state_creation_rune(rune)) {
if (seen.includes(name)) {
e.constructor_state_reassignment(node); // TODO the same thing applies to duplicate fields, so the code/message needs to change
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note to self

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants