Remove React PropTypes by using Flow Annotations (in CRA)

Flavio Corpa
InstructorFlavio Corpa
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 6 years ago

Starting from v15.5 if we wanted to use React's PropTypes we had to change our code to use a separate node module, now we can go one step further and get rid of that extra dependency just by using flow type annotations in our create-react-app project!

[00:01] Let's just install the Flow bin. Now that it's done, I'm going to go to my package.json file, and add the one script, Flow, run Flow. Now, we're going to go ahead and run npm run flow init. What this command is going to do, it's going to create this file, .flowconfig, that Flow needs to start working.

[00:31] What we have to do now is go to the file where we want to use Flow and use this small annotation, @flow. Because createReactApp comes out of the box with all this setup for using Flow in the project, we're just making sure that our editor or our IDE can read the annotations and type check our code.

[00:57] Babel's internal settings of createReactApp will make the rest for us, and will strip the type annotations when our code gets transpiled, which is pretty awesome. After adding this annotation, you will see that Flow already starts complaining, if you have props in your React component that are not typed.

[01:14] We can now finally remove our import prop types from prop types, and start typing out our Flow annotations. We're going to replace these with a type called button type, and get rid of all this, and of course, adapt this to Flow's syntax.

[01:43] One note here, Bool becomes Boolean. If not, it will be turned into any, and we definitely don't want that. Now, we can use our new button type in our React component, and everything start.

[02:02] Flow allows us to be even more explicit. For example, in our onClick function, we're going to tell Flow that we expect an event, and that we will return nothing, which is void. The last thing it complains is this last line.

[02:20] We don't want to use React built-in prop types anymore. Now, we save. We got rid of all the errors, and you can see how easy it was to get rid of your prop types dependency by using Flow type annotations in your createReactApp project.

Joonas Hamunen
Joonas Hamunen
~ 7 years ago

Any more coming? Specifically type checking in redux?

Flavio Corpa
Flavio Corpainstructor
~ 7 years ago

For sure! There are more goods on Flow coming, thanks for your interest! :)

James Talmage
James Talmage
~ 7 years ago

Is there a Babel plugin that hydrates propTypes to allow runtime type checking? Or are you simply relying on Flows static analysis?

Tony Brown
Tony Brown
~ 7 years ago

would love to see more about Flow with React

Markdown supported.
Become a member to join the discussionEnroll Today