When I first started learning TypeScript and using it with React, I followed patterns. A friend showed me how to type a component. I used that as an example whenever I created a new component. This example looked something like this:
Experimenting with this pattern, I thought to myself, “If I want to declare a component using the function keyword, then I bet I can do the same thing.”
Sadly, this is not valid. Instead of investigating deeper, I decided to stick with what worked (using function expressions like the first example). Eight months later, after diving deeper into TypeScript, I’ve finally learned the difference and understand why my first attempt didn’t work.
We’re annotating the function type because this variable holds a function. React.FC indicates a “React Function Component”. So that’s why we type it this way.
This time, we’re annotating the function return type. This explains why we can’t use the same type! We instead need to tell TypeScript, “Hey! This function here is going to return a React component.” So what does that look like? Like this:
These are all the valid things that can be returned by a component. Feel free to take a look at the source code here.
When your components accept props, it’s important to know where those get added in as well. Here’s an example:
We can do the same thing with a function declaration:
Pretty neat, huh?
LAST UPDATED: December 17, 2019