Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Missing return type on function" for every React class method

I a stateful React component in my Typescript project. I lint it with ESLint using @typescript-eslint/parser and @typescript-eslint/eslint-plugin. I've enabled the rule @typescript-eslint/explicit-function-return-type.

My component looks similar to this:

interface Props = {
  name: string;
}

interface State = {
  score: number
}

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

  componentDidMount() {
    ...
  }

  render() {
    ...
  }
}

In the above component I get the ESLint error on the componentDidMount and render methods:

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

I quite like the lint rule in general, but surely I don't have to declare a return type for all these React methods. I have @types/react and @types/react-dom installed, so aren't these return types covered already?

like image 376
CaribouCode Avatar asked Jun 21 '19 17:06

CaribouCode


2 Answers

Try writing the return type for render function as

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

This works for me!

like image 141
Gaurav Kalita Avatar answered Oct 19 '22 12:10

Gaurav Kalita


I just got it working by adding the rule into .eslintrc.json with

{ "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 }
    ]
  }
}

versions

"@typescript-eslint/eslint-plugin": "^1.10.2",
"@typescript-eslint/parser": "^1.10.2",
"eslint": "^6.0.0",
like image 4
Asaf Aviv Avatar answered Oct 19 '22 13:10

Asaf Aviv