As compilation (er…transpilation) becomes the defacto standard of the post ES5, JSX-leaning JS dev landscape—care of tools like Babel—there is a growing sentiment that it may be time to let go of our fair language’s dynamic and coercive ways in favor of a more sensible, statically-typed way of doing things.
Which leads to questions like, “Sure, but where do I even start?”
The biggest camps are TypeScript (Microsoft) and Flow (Facebook), but if you’re working in React you’ve already got a wonderful, low-maintenance alternative in your codebase that’s as easy to implement as it is to learn.
import React, { PropTypes } from 'react';
Say hello to React.PropTypes, a developer-friendly tool for declaring and checking types. Sure, it handles all the primitives ( array
, bool
, func
, number
, object
, string
, symbol
) easily enough:
function Nest({name}) {
return (
<div>
We called it {name}.
</div>
);
}
Nest.propTypes = {
name: PropTypes.string,
}
export default Nest;
But there’s also enough depth under the hood to manage some pretty sophisticated verifications:
Nest.propTypes = {
name: PropTypes.string,
eggs: PropTypes.shape({
species: PropTypes.string,
femaleToMale: PropTypes.arrayOf(PropTypes.number),
hobbies: PropTypes.oneOf(['swimming', 'stalking']),
}),
}
All-in you get nine additional types to throw your props against:
node
and element
for all your DOM and React element needsinstanceOf
for digging into prototypesoneOf
for lists of known potential valuesoneOfType
for lists of known potential typesarrayOf
and objectOf
for arrays and objects composed of a single typeshape
for objects in the shape of a specific schemaany
for when you really don’t want to check for a typeFurthermore, you can attach isRequired
to any PropType declaration for added rigidity.
hobbies: PropTypes.oneOf(['swimming', 'stalking']).isRequired
Couple things to note, PropType checking is disabled in production, and it’s only present as a guiding hand in development mode. It throws warnings, not errors.
👉 That’s it. You’re a type checking expert now. Don’t abuse this new power in opinion convos.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!