【问题标题】:Is there any rule like "explicit-function-return-type" without requiring void type?有没有像“explicit-function-return-type”这样的规则而不需要 void 类型?
【发布时间】:2020-01-16 07:59:45
【问题描述】:

是否有任何 ESLint 规则与 [explicit-function-return-type] 但函数上不需要 void 类型?

如果没有,我应该怎么做这个自定义规则?

【问题讨论】:

    标签: typescript eslint


    【解决方案1】:

    对于那些想要规则的人,我已经设法执行此自定义规则,但它目前仅适用于类内的方法。 我正在使用 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
      };
    };
    

    【讨论】:

      猜你喜欢
      • 2021-11-19
      • 2019-11-16
      • 2018-06-18
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 2014-06-01
      • 1970-01-01
      • 2011-01-04
      相关资源
      最近更新 更多