Skip to content

Rule to enforce type declaration of $state rune #1230

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
AntonioVentilii opened this issue May 19, 2025 · 3 comments
Open

Rule to enforce type declaration of $state rune #1230

AntonioVentilii opened this issue May 19, 2025 · 3 comments
Labels
enhancement New feature or request new rule

Comments

@AntonioVentilii
Copy link

Motivation

Is there a rule that enforces the declaration of the types for $state? If not, is it worth doing?

Description

For consistency, we could have a rule similar to prefer-reduce-type-parameter, that clearly enforces where to define the type of a $state variable.

Examples

<script>

  // BAD
  let title: string | undefined = $state();
  let data: { value?: number } = $state({})
  
  // GOOD
  let title = $state<string | undefined>();
  let data = $state<{ value?: number }>({});
  
  // UNCHANGED
  let label = $state(0)

</script>

Additional comments

No response

@AntonioVentilii AntonioVentilii added enhancement New feature or request new rule labels May 19, 2025
@dimfeld
Copy link

dimfeld commented Jun 12, 2025

Is there a reason that passing the type as a generic parameter is preferred? The docs suggest the "bad" way: https://svelte.dev/docs/svelte/typescript#Typing-$state

@baseballyama
Copy link
Member

Maybe we can refer to sveltejs/svelte#10694 to understand why we don’t use generics for runes.

@marekdedic
Copy link
Contributor

IMO, Rich's reasoning with inference doesn't apply to $state because unlike $props, the initializer value is a parameter and therefore TS will error out if it's incorrect.

However, IMHO, it's better to be consistent between $state and $props - so my preference would actually be a rule that does the exact opposite from the original proposal :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request new rule
Projects
None yet
Development

No branches or pull requests

4 participants