Skip to content
Advertisement

What is the difference between App: React.FunctionComponent and App = (): React.FunctionComponent?

Trying to understand typescript at the moment.

What is the difference between:

const App: React.FunctionComponent<CustomProps> = (props: CustomProps) => {
  return <div>Hello World!</div>;
};

and:

const App = (props: CustomProps): React.FunctionComponent => {
  return <div>Hello World!</div>;
};

The second one throws an error:

src/App.tsx:19:3 - error TS2322: Type 'Element' is not assignable to type 'FunctionComponent<{}>'.
  Type 'Element' provides no match for the signature '(props: { children?: ReactNode; }, context?: any): ReactElement<any, any> | null'.

Advertisement

Answer

const App: React.FunctionComponent<CustomProps> = (props: CustomProps)

means that App is a type of React.FunctionComponent<CustomProps>

const App = (props: CustomProps): React.FunctionComponent

means that your App is the type of any because you didn’t assign a type but it returns an object of type React.FuctionComponent

The error means that you return a JSX.Element and you said that the function return a FunctionComponent

The right code is :

const App: React.FunctionComponent<CustomProps> = (props: CustomProps): JSX.Element => {
  return <div>Hello World!</div>;
};

In addition, you can see directly what type your function is returned if you writte nothing on the return type. Is you have VS code you can hover your mouse on your function and it will display what it returns thanks to the intellisense

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement