React ยท Chapter 40 of 42

PropTypes & TypeScript

As apps grow, catching prop-related bugs early becomes valuable. React offers two common solutions: the `prop-types` library for runtime checking, and TypeScript for compile-time static typing.

TypeScript has become the more popular modern choice, offering autocomplete, refactoring safety, and catching errors before code ever runs.

PropTypes

`Component.propTypes = { name: PropTypes.string.isRequired }` warns in the console during development if the wrong prop type is passed.

TypeScript

Typing props with an interface (`interface Props { name: string }`) gives compile-time errors and excellent editor autocomplete.

Example 1 (tsx)
interface GreetingProps {
  name: string;
}

function Greeting({ name }: GreetingProps) {
  return <p>Hello, {name}!</p>;
}
Output
Hello, Ada!

TypeScript checks at compile time that `name` is always a string.

Key points

  • PropTypes provides runtime prop type checking in development.
  • TypeScript provides compile-time static type checking.
  • TypeScript is the more common modern choice for new React projects.
  • Both approaches help catch bugs from incorrect prop usage early.
๐Ÿ’ก Note: Vite's react-ts template sets up TypeScript with React out of the box.

๐Ÿ“ Quick Quiz

1. When does PropTypes checking happen?

2. What does TypeScript provide that PropTypes doesn't?

3. Which Vite template includes TypeScript for React?