azat-io / eslint-plugin-perfectionist

🦄 ESLint plugin for sorting various data such as objects, imports, types, enums, JSX props, etc.
https://eslint-plugin-perfectionist.azat.io
MIT License
1.62k stars 28 forks source link

Bug: sort-classes should consider initialization order #102

Open danvk opened 3 months ago

danvk commented 3 months ago

Describe the bug

If a class's properties include initializers, then perfectionist/sort-classes must consider references between those properties when sorting them.

Sorting property a before property z is incorrect if z references a in its initializer (see code sample below).

Code example

perfectionist/sort-classes reports an error on this class:

class C {
  z = new Date();
  a = this.z;
}
// Expected "a" to come before "z"

Autofixing the error "corrects" the class to this:

class C {
  a = this.z;
  //       ~ Property 'z' is used before its initialization.ts(2729)
  z = new Date();
}

But this has a type error and a will be undefined at runtime.

ESLint version

v8.56.0

ESLint Plugin Perfectionist version

v2.5.0

Additional comments

What's the correct behavior here? Ideal behavior would be to sort as usual while still preserving the initialization graph. Maybe slightly easier would be to preserve the relative order of any properties that reference another one in their initializer, or are referenced in an initializer.

Validations

Tragio commented 2 months ago

I'm facing a similar issue in our codebase. @azat-io do you have any fix in the works? 😄

Thank you for your amazing work!! 🙏

azat-io commented 2 months ago

I'll try to get on that early next week