有没有什么ESLint规则可以和显式函数返回类型做同样的事情,但不需要在函数上使用空类型?
如果没有,我应该如何执行此自定义规则?
发布于 2019-12-14 07:18:45
对于那些需要规则的人,我已经设法完成了这个自定义规则,但它目前只适用于类中的方法。我使用的是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
};
};https://stackoverflow.com/questions/57940623
复制相似问题