每个 React 类方法的“缺少函数返回类型”

IT技术 javascript reactjs typescript
2021-05-15 13:36:44

我的 Typescript 项目中有一个有状态的 React 组件。我使用 ESLint@typescript-eslint/parserlint 它@typescript-eslint/eslint-plugin我已经启用了规则@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安装了,所以这些返回类型不是已经涵盖了吗?

3个回答

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

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

这对我有用!

我只是通过将规则添加到.eslintrc.jsonwith

{ "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",

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