Validate React Props With PropTypes and TypeScript

This lesson preview is part of the The newline Guide to Building a Company Component Library course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.

This video is available to students only
Unlock This Course

Get unlimited access to The newline Guide to Building a Company Component Library, plus 70+ \newline books, guides and courses with the \newline Pro subscription.

Thumbnail for the \newline course The newline Guide to Building a Company Component Library
  • [00:00 - 00:56] When developing with TypeScript, you will often see teams stop using Prop types for runtime prop validation. TypeScript does an excellent job of enforcing prop constraints for other TypeScript consumers, but our library may be consumed by both TypeScript and JavaScript code bases in the future. To ensure that all consumers have prop validation, we will be including prop types for our components. Let's install prop types as a common dependency. Then we can add prop type validation to our button component by including prop types up above, and then defining a prop type declaration down here, button.prop types. These values are going to be inferred from the button props interface that we defined above.

    [00:57 - 02:02] If we do variant, we do prop types, one of which is an array of values. This could be secondary, primary, danger. This will fail if it doesn't match the values that are applied above, so we did danger123. This wouldn't be a valid prop type. Danger aligns it with what we have above size. We do another prop type, one of small, medium, or large. Then is full width which would be a prop types rule. Now we have TypeScript prop checking for at build time. We also have prop type checking with prop types for our runtime checks. This will work for both JavaScript and TypeScript consumers. Let's go and save our progress by creating a new commit. In the next module, we are going to be creating more advanced shared components with the compound component pattern and react context.