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

Coo*_*oop 14 javascript typescript reactjs

我的 Typescript 项目中有一个有状态的 React 组件。我使用 ESLint@typescript-eslint/parser和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() {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

小智 12

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

render(): JSX.Element {
  // render code
}
Run Code Online (Sandbox Code Playgroud)

这对我有用!