@lsby/eslint-plugin 0.0.21 → 0.0.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
2
|
+
// 禁止对于等于/不等于条件的 else 处理多种状态
|
|
3
|
+
// 因为对于这些条件,else 表示"除给定状态外的所有可能"
|
|
4
|
+
// 对于状态小于等于两个的条件, else 只会兜底一种情况, 这是正确的
|
|
5
|
+
// 但如果状态继续增加, else 兜底必然匹配一个以上种状态
|
|
6
|
+
// 此时 else 部分会默默吃掉新增状态却无任何提示, 这很容易造成意外的状态逻辑遗漏
|
|
7
|
+
// 这种情况下应当使用提早返回 或 switch + 穷尽检查
|
|
7
8
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
8
9
|
if (k2 === undefined) k2 = k;
|
|
9
10
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
@@ -42,10 +43,10 @@ const ts = __importStar(require("typescript"));
|
|
|
42
43
|
const rule = {
|
|
43
44
|
meta: {
|
|
44
45
|
type: 'problem',
|
|
45
|
-
docs: {
|
|
46
|
-
|
|
47
|
-
noElse: '禁止在等于/不等于条件下使用 else 分支。当条件状态扩展到多于2个时, else部分会默默吃掉新增状态却无任何提示。请改用提前返回(early return)或 switch 语句',
|
|
46
|
+
docs: {
|
|
47
|
+
description: '禁止对等于/不等于条件使用 else。当新增状态时,else 会隐匿地处理新状态,容易造成状态逻辑遗漏。应使用提早返回或 switch + 穷尽检查替代。',
|
|
48
48
|
},
|
|
49
|
+
messages: { noElse: '禁止在等于/不等于条件中使用 else,请使用提早返回或 switch 语句进行穷尽检查。' },
|
|
49
50
|
schema: [],
|
|
50
51
|
},
|
|
51
52
|
defaultOptions: [],
|
|
@@ -59,12 +60,21 @@ const rule = {
|
|
|
59
60
|
// 先检查联合类型,因为它可能包含其他标志
|
|
60
61
|
if ((type.flags & ts.TypeFlags.Union) !== 0) {
|
|
61
62
|
const union = type;
|
|
62
|
-
|
|
63
|
+
// Count distinct types in union
|
|
64
|
+
let count = 0;
|
|
65
|
+
for (const t of union.types) {
|
|
66
|
+
count += countLiteralVariants(t);
|
|
67
|
+
}
|
|
68
|
+
return count;
|
|
63
69
|
}
|
|
64
70
|
// 布尔类型有 2 个值:true 和 false
|
|
65
71
|
if ((type.flags & ts.TypeFlags.Boolean) !== 0) {
|
|
66
72
|
return 2;
|
|
67
73
|
}
|
|
74
|
+
// 布尔字面量类型(true 或 false)
|
|
75
|
+
if ((type.flags & ts.TypeFlags.BooleanLiteral) !== 0) {
|
|
76
|
+
return 1;
|
|
77
|
+
}
|
|
68
78
|
// null 类型(1 个值)
|
|
69
79
|
if ((type.flags & ts.TypeFlags.Null) !== 0) {
|
|
70
80
|
return 1;
|
|
@@ -74,8 +84,7 @@ const rule = {
|
|
|
74
84
|
return 1;
|
|
75
85
|
}
|
|
76
86
|
// 字面量类型
|
|
77
|
-
if ((type.flags & (ts.TypeFlags.StringLiteral | ts.TypeFlags.NumberLiteral
|
|
78
|
-
0) {
|
|
87
|
+
if ((type.flags & (ts.TypeFlags.StringLiteral | ts.TypeFlags.NumberLiteral)) !== 0) {
|
|
79
88
|
return 1;
|
|
80
89
|
}
|
|
81
90
|
// 其他类型(如 number、string 等)认为是无限的
|