首页 > 解决方案 > 每个 React 类方法的“函数缺少返回类型”

问题描述

我的 Typescript 项目中有一个有状态的 React 组件。我使用 ESLint 使用@typescript-eslint/parserand对它进行 lint @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() {
    ...
  }
}

在上面的组件中,我在componentDidMountandrender方法上得到 ESLint 错误:

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

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

标签: javascriptreactjstypescript

解决方案


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

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

这对我有用!


推荐阅读