In React, PropTypes is a way to check the data types of props that a component receives.
It helps you catch bugs by warning you if the wrong type of data is passed to a component.
Why use PropTypes?
- Ensures components get the right type of data.
- Provides documentation for other developers.
- Helps in debugging unexpected prop values.
How to use PropTypes
- Import
prop-typespackage:
npm install prop-types
- Example in a component:
import React from "react";
import PropTypes from "prop-types";
function Student(props) {
return (
<div>
<p>Name: {props.name}</p>
<p>Age: {props.age}</p>
<p>Student: {props.isStudent ? "Yes" : "No"}</p>
</div>
);
}
// Setting PropTypes
Student.propTypes = {
name: PropTypes.string.isRequired, // must be a string
age: PropTypes.number, // must be a number
isStudent: PropTypes.bool // must be true/false
};
// Default props
Student.defaultProps = {
age: 18,
isStudent: false
};
export default Student;
Common PropTypes
-
PropTypes.string→ string -
PropTypes.number→ number -
PropTypes.bool→ true/false -
PropTypes.array→ array -
PropTypes.object→ object -
PropTypes.func→ function -
PropTypes.node→ anything that can be rendered (elements, strings, numbers) -
PropTypes.element→ React element -
PropTypes.oneOf(["a", "b"])→ one specific value -
PropTypes.arrayOf(PropTypes.number)→ array of numbers -
PropTypes.shape({ key: PropTypes.string })→ object with specific structure
PropTypes vs TypeScript in React
| Feature | PropTypes | TypeScript |
|---|---|---|
| What it is | A separate library (prop-types) for runtime type checking |
A superset of JavaScript that adds static typing |
| Type Checking | Happens at runtime → shows warnings in the console when props are invalid | Happens at compile-time → errors before running the code |
| Scope | Only checks props in React components | Checks props + state + functions + variables + entire codebase |
| Installation | npm install prop-types |
npm install typescript |
| Ease of Use | Lightweight, simple, no extra setup | More setup (tsconfig.json, type definitions) |
| Best For | Small projects, quick prop validation | Large projects, full-scale type safety |
Interview-Friendly Answer (30 sec)
“PropTypes is a library in React for runtime type checking of props, whereas TypeScript provides compile-time type safety for the entire codebase, not just props. PropTypes is simpler and useful in small projects, but TypeScript is preferred in modern large-scale applications because it prevents errors before running the code.”
Top comments (0)