forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathonly-arrow-functions.cjs
More file actions
85 lines (73 loc) · 2.89 KB
/
only-arrow-functions.cjs
File metadata and controls
85 lines (73 loc) · 2.89 KB
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
77
78
79
80
81
82
83
84
85
const { AST_NODE_TYPES, TSESTree } = require("@typescript-eslint/utils");
const { createRule } = require("./utils.cjs");
module.exports = createRule({
name: "only-arrow-functions",
meta: {
docs: {
description: `Disallows traditional (non-arrow) function expressions.`,
},
messages: {
onlyArrowFunctionsError: "non-arrow functions are forbidden",
},
schema: [{
additionalProperties: false,
properties: {
allowNamedFunctions: { type: "boolean" },
allowDeclarations: { type: "boolean" },
},
type: "object",
}],
type: "suggestion",
},
/** @type {[{ allowNamedFunctions?: boolean; allowDeclarations?: boolean }]} */
defaultOptions: [{
allowNamedFunctions: false,
allowDeclarations: false,
}],
create(context, [{ allowNamedFunctions, allowDeclarations }]) {
/** @type {(node: TSESTree.FunctionDeclaration | TSESTree.FunctionExpression) => boolean} */
const isThisParameter = node => node.params.some(param => param.type === AST_NODE_TYPES.Identifier && param.name === "this");
/** @type {(node: TSESTree.Node) => boolean} */
const isMethodType = node => {
const types = [
AST_NODE_TYPES.MethodDefinition,
AST_NODE_TYPES.Property,
];
const parent = node.parent;
if (!parent) {
return false;
}
return node.type === AST_NODE_TYPES.FunctionExpression && types.includes(parent.type);
};
/** @type {boolean[]} */
const stack = [];
const enterFunction = () => {
stack.push(false);
};
const markThisUsed = () => {
if (stack.length) {
stack[stack.length - 1] = true;
}
};
/** @type {(node: TSESTree.FunctionDeclaration | TSESTree.FunctionExpression) => void} */
const exitFunction = node => {
const methodUsesThis = stack.pop();
if (node.type === AST_NODE_TYPES.FunctionDeclaration && allowDeclarations) {
return;
}
if ((allowNamedFunctions && node.id !== null) || isMethodType(node)) { // eslint-disable-line no-null/no-null
return;
}
if (!(node.generator || methodUsesThis || isThisParameter(node))) {
context.report({ messageId: "onlyArrowFunctionsError", node });
}
};
return {
"FunctionDeclaration": enterFunction,
"FunctionDeclaration:exit": exitFunction,
"FunctionExpression": enterFunction,
"FunctionExpression:exit": exitFunction,
"ThisExpression": markThisUsed,
};
},
});