【问题标题】:"Missing return type on function" for every React class method每个 React 类方法的“函数缺少返回类型”
【发布时间】:2023-03-25 12:25:01
【问题描述】:

我是我的 Typescript 项目中的一个有状态的 React 组件。我使用 ESLint 使用 @typescript-eslint/parser@typescript-eslint/eslint-plugin 对其进行 lint。我已启用规则@typescript-eslint/explicit-function-return-type

我的组件看起来像这样:

interface Props = {
  name: string;
}

interface State = {
  score: number
}

class Person extends Component<Props, State> {
  state = {
    score: 2,
  };

  componentDidMount() {
    ...
  }

  render() {
    ...
  }
}

在上述组件中,componentDidMountrender 方法出现 ESLint 错误:

Missing return type on function - @typescript-eslint/explicit-function-return-type

总的来说,我非常喜欢 lint 规则,但我当然不必为所有这些 React 方法声明返回类型。我已经安装了@types/react@types/react-dom,那么这些返回类型不是已经涵盖了吗?

【问题讨论】:

  • 您是否检查了允许继承类型选项的设置?
  • @AvinKavish 我还没有检查过,但现在会检查。我的 ESLint 扩展是:"plugin:react/recommended", "plugin:@typescript-eslint/recommended" 所以虽然这将是默认值?!
  • 哦,我的意思是在您安装的插件中​​,没关系我刚刚检查过,它没有这样的选项。您可能需要考虑在 GitHub 上打开一个问题并直接询问作者。
  • @AvinKavish 好的,感谢您的帮助

标签: javascript reactjs typescript


【解决方案1】:

我刚刚通过将规则添加到 .eslintrc.json 中来实现它

{ "allowTypedFunctionExpressions": true }

.eslintrc.json

{
  "parser": "@typescript-eslint/parser",
  "extends": ["plugin:@typescript-eslint/recommended"],
  "plugins": ["@typescript-eslint"],
  "rules": {
    "@typescript-eslint/explicit-function-return-type": [
      "error",
      { "allowTypedFunctionExpressions": true }
    ]
  }
}

版本

"@typescript-eslint/eslint-plugin": "^1.10.2",
"@typescript-eslint/parser": "^1.10.2",
"eslint": "^6.0.0",

【讨论】:

    【解决方案2】:

    尝试将渲染函数的返回类型写为

    render(): JSX.Element {
      // render code
    }
    

    这对我有用!

    【讨论】:

    • 我收到JSX is not defined
    【解决方案3】:

    我在这里可能是错的,因为我没有亲自使用过@typescript-eslint/explicit-function-return-type,但它的名字听起来好像你在每个编写的函数中都需要一个return,包括生命周期方法。请记住,ESLint 和 React 并不相同。 ESLint 只是在您的代码上运行以指出潜在 错误。如果不包含这些 return 语句,React 库应该仍然可以正常运行

    【讨论】:

    • 我认为您没有理解这个问题。他说类型推断应该适用于类,因为他继承自 Component,后者已经使用返回类型定义了这些方法
    • 这是一个 linting 问题,与代码是否会运行无关。 @types/react 定义了 componentDidMount 的类型,包括返回类型。那么 linting 怎么会告诉我重新定义它呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 2013-03-31
    • 1970-01-01
    • 2021-06-27
    • 2020-04-04
    • 1970-01-01
    • 2021-07-05
    相关资源
    最近更新 更多