PropTypes in a TypeScript React Application

Typescript and PropTypes serve different purposes. Typescript validates types at compile time, whereas PropTypes are checked at runtime.

Typescript is useful when you are writing code: it will warn you if you pass an argument of the wrong type to your React components, give you autocomplete for function calls, etc.

PropTypes are useful when you test how the components interact with external data, for example when you load JSON from an API. PropTypes will help you debug (when in React’s Development mode) why your component is failing by printing helpful messages like:

Warning: Failed prop type: Invalid prop `id` of type `number` supplied to `Table`, expected `string`

Even though it may seem like Typescript and PropTypes do the same thing, they don’t actually overlap at all. But it is possible to automatically generate PropTypes from Typescript so that you don’t have to specify types twice, see for example:

  • https://github.com/milesj/babel-plugin-typescript-to-proptypes
  • https://github.com/grncdr/ts-react-loader#what-it-does
  • https://github.com/gcanti/prop-types-ts

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)