explicit-function-return-type creating functional component react in typescript

const App: FC = () => {
   const addItem = () => {
      useState([...items, {id:1,name:'something'])
   }
   return<div>hello</div>
}

linter gave me error, on my App.tsx.

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

I have to turn off explicit-function-return-type, how to fix above code? The AddItem doesn’t have to return something.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

I am not sure which version of react are you using, but the so-called right way of providing typings for your Functional Components using TypeScript and React 16.8 would be to use React.FC or React.FunctionComponent. The following would run fine on most TsLint configs. You can try using the below on your project that runs on @typescript-eslint

import * as React from 'react';

const App: React.FC = () => {
   // do something

   return <div>hello</div>;
}

However, if the above does not work, you may be required to explicitly type the return value by doing the following:

import * as React from 'react';

const App: React.FC = (): JSX.Element => {
   // do something

   return <div>hello</div>;
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply