When using function components in React, we may want to type their props with TypeScript. Overall there are two ways of making a React component type safe with TypeScript, however, letâs start by converting the following JavaScript React component to a TypeScript React component as leading example:
The straightforward yet most verbose way of typing this React component would be inlining the types in the functional componentâs function signature:
From there, we would start extracting reusable types from the functional componentâs function signature into a standalone TypeScript type. Itâs up to you whether you prefer using a type or interface:
Since React props are just a JavaScript object, we can extract a type respectively to the React function componentâs props too:
In the beginning I mentioned that there are two ways of make a React component type safe. The last code snippet already showed you one way of doing it. A more popular way would be using TypeScriptâs type annotation syntax:
After all, the syntax is up to you and your team. It would be important to align on one way of doing it though. Last but not least, you can also define a React componentâs return type even though it is usually inferred:
Thatâs it. You can make a function componentâs props type safe in TypeScript by using a type or interface. We have used the former here. In addition, you have two variations of defining types that I have presented here. Last but not least, you can optionally type a function componentâs return type.