How to Define Props in React + TypeScript App

Props in React are like function arguments. They are passed in a component so it knows the data to work with.

To define props create a new type where declare every prop that should be defined:

The name for this type consists of 2 parts:

  • Component prefix, which is the name of the component being described;

  • Props postfix, that describes the intent of this type.

It is now a good convention to name props types like this.

Props Types Usage#

To use a props type pass it as a type for components props:

You also can use FunctionComponent and FC generic types for it:

Complex Props#

To define a props type with complex structures inside, it is better to decompose those structures in multiple different types. For example:

You can use these types in component declaration as usual.

Optional Props#

You can declare optional props using ?:

Types vs Interfaces#

You can use an interface as well as a type for declaring props types:

The difference between a type and an interface is in their extension. Let's say you want to extend ComponentProps with another field baz.

In a case of a type you would write:

In a case of an interface:

On the contrary, an interface cannot extend a union type:

Sources#