-
Notifications
You must be signed in to change notification settings - Fork 3
/
node-param-array-type-assertion.ts
76 lines (67 loc) · 1.78 KB
/
node-param-array-type-assertion.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { AST_NODE_TYPES, TSESTree } from "@typescript-eslint/utils";
import { utils } from "../ast/utils";
import { id } from "../ast/identifiers";
export default utils.createRule({
name: utils.getRuleName(module),
meta: {
type: "problem",
docs: {
description: "Array of node parameters must be typed, not type-asserted.",
recommended: "strict",
},
fixable: "code",
schema: [],
messages: {
typeArray: "Use ': INodeProperties[]' [autofixable]",
},
},
defaultOptions: [],
create(context) {
return {
TSAsExpression(node) {
if (containsArrayOfNodeParams(node)) {
if (
node.parent?.type !== AST_NODE_TYPES.VariableDeclarator ||
node.parent?.id.type !== AST_NODE_TYPES.Identifier
) {
return;
}
const rangeToRemove = utils.getRangeToRemove({
ast: node.typeAnnotation,
});
const { range } = node.parent.id;
if (!range) return null;
const indentation = getTrailingBracketIndentation(node);
context.report({
messageId: "typeArray",
node,
fix: (fixer) => {
// double fix
return [
fixer.replaceTextRange(rangeToRemove, indentation),
fixer.insertTextAfterRange(range, ": INodeProperties[]"),
];
},
});
}
},
};
},
});
function containsArrayOfNodeParams(node: TSESTree.TSAsExpression) {
if (
node.expression.type !== AST_NODE_TYPES.ArrayExpression ||
node.expression.elements.length === 0
) {
return false;
}
return node.expression.elements.every((element) => {
return (
element?.type === AST_NODE_TYPES.ObjectExpression &&
id.isNodeParameter(element)
);
});
}
function getTrailingBracketIndentation(node: TSESTree.TSAsExpression) {
return "\t".repeat(node.expression.loc.end.column - 1); // `- 1` to remove bracket column
}