【发布时间】:2020-01-16 07:59:45
【问题描述】:
是否有任何 ESLint 规则与 [explicit-function-return-type] 但函数上不需要 void 类型?
如果没有,我应该怎么做这个自定义规则?
【问题讨论】:
标签: typescript eslint
是否有任何 ESLint 规则与 [explicit-function-return-type] 但函数上不需要 void 类型?
如果没有,我应该怎么做这个自定义规则?
【问题讨论】:
标签: typescript eslint
对于那些想要规则的人,我已经设法执行此自定义规则,但它目前仅适用于类内的方法。 我正在使用 Angular 应用程序,所以它工作得很好。
const expUtil = require("@typescript-eslint/experimental-utils");
module.exports = (context) => {
/**
* Checks if a node is a constructor.
* @param node The node to check
*/
function isConstructor(node) {
return (!!node &&
node.type === expUtil.AST_NODE_TYPES.MethodDefinition &&
node.kind === 'constructor');
}
/**
* Checks if a node is a setter.
*/
function isSetter(node) {
return (!!node &&
(node.type === expUtil.AST_NODE_TYPES.MethodDefinition ||
node.type === expUtil.AST_NODE_TYPES.Property) &&
node.kind === 'set');
}
/**
* Checks if a node is returning some value
*/
function isReturningValue(node) {
const content = node.value.body;
const returnVal = content.body.find(n =>
n.type === expUtil.AST_NODE_TYPES.ReturnStatement
);
return (returnVal && !!returnVal.argument);
}
/**
* Checks if a function declaration/expression has a return type.
*/
function checkFunctionReturnType(node) {
if (node.returnType ||
node.value.returnType ||
isConstructor(node.parent) ||
isSetter(node.parent)) {
return;
}
if (!isReturningValue(node)) {
return;
}
context.report(
node, 'Functions of type void should not return any value'
);
}
return {
MethodDefinition: checkFunctionReturnType
};
};
【讨论】: