mskelton / eslint-plugin-sort

Auto-fixable sort rules for ESLint.
https://www.npmjs.com/package/eslint-plugin-sort
ISC License
24 stars 1 forks source link

Sort Enum Properties #26

Closed seanblonien closed 2 years ago

seanblonien commented 2 years ago

I love this eslint plugin and how it sorts so much more than other eslint rules/plugins that I've tried.

I am using it to sort type interface properties, but it currently doesn't work on sorting enums within TypeScript. Is this something that exists or something that could be added easily?

Example enum code:

export enum MyEnum {
  z,
  b,
  a,
}

with rule that would auto-fix/give warning/error about the properties not being sorted, and turn into:

export enum MyEnum {
  a,
  b,
  z,
}
mskelton commented 2 years ago

So, enum sorting is tricky as it changes runtime behavior. Given your first example, the value of each key is:

export enum MyEnum {
  z, // 0
  b, // 1
  a, // 2
}

If you sort it, that changes:

export enum MyEnum {
  a, // 0
  b, // 1
  z, // 2
}

As you can see, the runtime value of each enum property changes. This other ESLint plugin has a rule for sorting string enums which are safe since the value of each property is explicit.

I never implemented this due to fact that I personally don't use enums so it wasn't something I really cared to implement. If you are interested in implementing sorting for string enums, I'd happily merge it, but I likely won't add it myself.

seanblonien commented 2 years ago

Ah yes, I forgot it would change the enum values unless they were named, you're right.

Yea that other ESLint plugin pretty much solves my use case for it, so I think I'll just use that plugin. I also don't have too much interest in implementing it myself.