@lsby/eslint-plugin 0.0.21 → 0.0.23
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
|
+
// 这种情况下应当使用提早返回(early return)或 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,9 +43,11 @@ const ts = __importStar(require("typescript"));
|
|
|
42
43
|
const rule = {
|
|
43
44
|
meta: {
|
|
44
45
|
type: 'problem',
|
|
45
|
-
docs: {
|
|
46
|
+
docs: {
|
|
47
|
+
description: '禁止在非二值状态的等于/不等于条件中使用 else。当状态扩张时,else 会隐匿地处理新状态,容易造成状态逻辑遗漏。',
|
|
48
|
+
},
|
|
46
49
|
messages: {
|
|
47
|
-
noElse: '
|
|
50
|
+
noElse: '禁止在非二值状态的等于/不等于条件中使用 else。若逻辑本质为二值状态,请先通过辅助变量表示为布尔值;若为多状态逻辑,请使用提早返回(early return)或 switch 穷尽。',
|
|
48
51
|
},
|
|
49
52
|
schema: [],
|
|
50
53
|
},
|
|
@@ -59,12 +62,21 @@ const rule = {
|
|
|
59
62
|
// 先检查联合类型,因为它可能包含其他标志
|
|
60
63
|
if ((type.flags & ts.TypeFlags.Union) !== 0) {
|
|
61
64
|
const union = type;
|
|
62
|
-
|
|
65
|
+
// Count distinct types in union
|
|
66
|
+
let count = 0;
|
|
67
|
+
for (const t of union.types) {
|
|
68
|
+
count += countLiteralVariants(t);
|
|
69
|
+
}
|
|
70
|
+
return count;
|
|
63
71
|
}
|
|
64
72
|
// 布尔类型有 2 个值:true 和 false
|
|
65
73
|
if ((type.flags & ts.TypeFlags.Boolean) !== 0) {
|
|
66
74
|
return 2;
|
|
67
75
|
}
|
|
76
|
+
// 布尔字面量类型(true 或 false)
|
|
77
|
+
if ((type.flags & ts.TypeFlags.BooleanLiteral) !== 0) {
|
|
78
|
+
return 1;
|
|
79
|
+
}
|
|
68
80
|
// null 类型(1 个值)
|
|
69
81
|
if ((type.flags & ts.TypeFlags.Null) !== 0) {
|
|
70
82
|
return 1;
|
|
@@ -74,8 +86,7 @@ const rule = {
|
|
|
74
86
|
return 1;
|
|
75
87
|
}
|
|
76
88
|
// 字面量类型
|
|
77
|
-
if ((type.flags & (ts.TypeFlags.StringLiteral | ts.TypeFlags.NumberLiteral
|
|
78
|
-
0) {
|
|
89
|
+
if ((type.flags & (ts.TypeFlags.StringLiteral | ts.TypeFlags.NumberLiteral)) !== 0) {
|
|
79
90
|
return 1;
|
|
80
91
|
}
|
|
81
92
|
// 其他类型(如 number、string 等)认为是无限的
|