查看eslint的文档 排序键 我可以让Visual Studio代码在行上报错。a
:
const obj = {
b: '2',
a: '1', // not sorted !
c: '3',
d: '4',
};
是否有办法实现同样的行为?enum
:
/* eslint sort-keys: "error" */
const enum obj {
b= '2',
a= '1', // no warning !
c= '3',
d= '4',
};
/* eslint-disable sort-keys */
更新:从我的问题描述中可能看不清楚,但我的枚举是基于字符串的。
你应该看看 eslint-plugin-typescript-sort-keys。更多关于规则的细节 此处.我还没有试过,但它似乎可以做到你想要的。
如果你使用的是TypeScript,也许最好是使用 TSLint 而不是ESLint。
您仍然可以使用您的一些 ESLint
规则与 tslint-eslint-rules
.
然后您可以添加 @crazyfactory/tslint-rules
其具有 enum-sort-keys
规则,其作用与 object-literal-sort-keys
但对于 enum
:
// Passes:
enum Character {
AAA = "aaa",
BBB = "bbb",
CCC = "ccc"
}
// Fails:
enum Character {
AAA = "aaa",
CCC = "ccc", <- The key "CCC" is not sorted alphabetically.
BBB = "bbb"
}
// Passes:
enum Number {
ONE,
THREE,
TWO
}
// Fails:
enum Number {
ONE,
TWO, <- The key "TWO" is not sorted alphabetically.
THREE
}
并不是对你的问题的直接回答,但是用TypeScript你可以通过不声明所有的值来实现隐式排序。例如,根据 公文 你可以做。
enum Direction {
Up = 1,
Down,
Left,
Right,
}
而这将是隐性的排序。