DEV Community

Shubham Pandey
Shubham Pandey

Posted on

React Type Checking

No Type checking -> Perk of using a dynamic language like Javascript.

But as your app grows, you start facing issues/bugs due to mishandling of type in props passed.

If you have nested prop passing boom 💥 .

Thankfully, React comes with built-in type checking abilities.

React uses prop-types library to implement type-checking.



import React from "react"
import Cart from "./Cart"

function App() {
    return (
            <Card price={400} title="Watch"}/>
            <Card price={600} title="Perfume"/>
            <Card price={1000} title="Mouse"/>

export default App
Enter fullscreen mode Exit fullscreen mode

Here is a basic shopping cart example where each card represents single item with a title and a price.


import React from "react"
import PropTypes from "prop-types"

const Cart = (props) => {
  const { title, price } = props;
  return (

Cart.propTypes = {
    title: PropTypes.string.isRequired,
    price: PropTypes.number

export default Cart

Enter fullscreen mode Exit fullscreen mode

PropTypes supports various validation and other handy code chunks.

Let's say we wanted our price to be one of 200,600,400

Cart.propTypes = {
    price: PropTypes.oneOf([200,300,400])
Enter fullscreen mode Exit fullscreen mode

Find other various use cases for PropTypes Link


  • Usage may vary as per your need but these are handy react-y way of type checks.😁

Top comments (0)