Video Tutorial Validate properties
In this chapter we will see how to validate types using prop-types
. As your application grows, and the number of components increases, errors may creep into your props.
function Add1Component ({n}) {
return I added 1 to the number: {n + 1}
}
// Will display 11 instead of 2 because the property should be a number
Flow or Typescript
The first strategy to make your code safer is to use tools like Flow or TypeScript that allow you to specify the types of your variables and function parameters. These tools allow static code analysis to detect type inconsistencies without having to run the code.
PropTypes
PropTypes offers a set of validators that allow you to validate the types of properties at runtime.
function Add1Component ({n}) {
return I added 1 to the number: {n + 1}
}
Add1Component.propTypes = {
n: PropTypes.number.isRequired
};
This validation returns errors when the component receives properties that do not correspond to the defined signature.