首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有没有像“显式函数返回类型”这样不需要void类型的规则?

有没有像“显式函数返回类型”这样不需要void类型的规则?
EN

Stack Overflow用户
提问于 2019-09-15 10:11:45
回答 1查看 405关注 0票数 5

有没有什么ESLint规则可以和显式函数返回类型做同样的事情,但不需要在函数上使用空类型?

如果没有,我应该如何执行此自定义规则?

EN

回答 1

Stack Overflow用户

发布于 2019-12-14 07:18:45

对于那些需要规则的人,我已经设法完成了这个自定义规则,但它目前只适用于类中的方法。我使用的是Angular应用程序,所以它工作得很好。

代码语言:javascript
复制
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
  };
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57940623

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档