Skip to content

Class state has a fundamental typing flaw #12655

Closed
@elliott-with-the-longest-name-on-github

Description

Describe the bug

Consider the following example:

export class Foo {
  count: number; // Property 'count' has no initializer and is not definitely assigned in the constructor.(2564)

  constructor() {};
}

In with a Svelte class, there is no way I can find to declare class fields in this way:

export class Foo {
  count: number;

  constructor(initialCount) {
    this.count = $state(initialCount); // `$state(...)` can only be used as a variable declaration initializer or a class field
  }
}

Doesn't work, because $state can't be used in the constructor.

export class Foo {
  count: number = $state(); // typeof count === number | undefined, even though it's _not_ undefined-able. You also lose the constructor assignment analysis

  constructor(initialCount) {
    this.count = initialCount;
  }
}

This seems like a bit of a critical issue for typing classes; there's no way I can find to create a class state property that's assigned in the constructor without adding undefined to its type.

Reproduction

See description.

Logs

No response

System Info

N/A

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions