-
Notifications
You must be signed in to change notification settings - Fork 12.2k
/
type-operator-spacing.ts
43 lines (37 loc) · 1.4 KB
/
type-operator-spacing.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { TSESTree, AST_TOKEN_TYPES } from "@typescript-eslint/utils";
import { createRule } from "./utils";
export = createRule({
name: "type-operator-spacing",
meta: {
docs: {
description: ``,
recommended: "error",
},
messages: {
typeOperatorSpacingError: `The '|' and '&' operators must be surrounded by spaces`,
},
schema: [],
type: "suggestion",
},
defaultOptions: [],
create(context) {
const sourceCode = context.getSourceCode();
const tokens = ["|", "&"];
const text = sourceCode.getText();
const checkTypeOperatorSpacing = (node: TSESTree.TSIntersectionType | TSESTree.TSUnionType) => {
node.types.forEach(node => {
const token = sourceCode.getTokenBefore(node);
if (!!token && token.type === AST_TOKEN_TYPES.Punctuator && tokens.indexOf(token.value) >= 0) {
const [start, end] = token.range;
if (/\S/.test(text[start - 1]) || /\S/.test(text[end])) {
context.report({ messageId: "typeOperatorSpacingError", node: token });
}
}
});
};
return {
TSIntersectionType: checkTypeOperatorSpacing,
TSUnionType: checkTypeOperatorSpacing,
};
},
});