How to create a functional component using TypeScript

Create a new file with a component name, for example, Message.tsx. It is important to use the .tsx extension for the component to work properly.

Inside, create a functional component as you would in plain React:

Then, create a MessageProps type to define props that this component will accept. Use it to type passed props inside of a component:

The MessageProps type is used to declare what type the properties of this component support.

This is similar to declaring types with prop-types but without any additional packages and the result of type checking is available at design time. You won't need to run the project to figure out that some types are not correctly passed.

Generic types#

Also, you can use React's FunctionComponent generic type to avoid typing props themselves and shorten the declaration a bit:

This generic type will help TypeScript to derive props types.

Similar, you can use FC generic, which is the same as FunctionComponent but shorter:


Those generics support children prop. So, you don't have to manually define it in your component props if you need it.