1

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'.

1 Answer 1

4
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

Sign up to request clarification or add additional context in comments.

1 Comment

In addition to this answer check react-typescript-cheatsheet.netlify.app/docs/basic/… for more ts-react info

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.