Advertisement
Advanced TypeScript, Migrating JavaScript to TypeScript

How do you convert PropTypes-based type checking (common in older React codebases) into equivalent TypeScript types during migration?

Short answer

Translate each PropTypes validator into an equivalent TypeScript interface member: PropTypes.string.isRequired becomes `name: string`, PropTypes.func becomes an optional function type, PropTypes.shape({...}) becomes a nested interface — then remove the runtime PropTypes checks…

Save TypeScript mock interview
Advertisement
AModel answer
Translate each PropTypes validator into an equivalent TypeScript interface member: PropTypes.string.isRequired becomes `name: string`, PropTypes.func becomes an optional function type, PropTypes.shape({...}) becomes a nested interface — then remove the runtime PropTypes checks entirely, since TypeScript now enforces the same contract at compile time (with the trade-off of losing PropTypes' runtime warnings for genuinely untyped external data).
// Before (PropTypes)
UserCard.propTypes = {
  name: PropTypes.string.isRequired,
  onClick: PropTypes.func
};

// After (TypeScript)
interface UserCardProps {
  name: string;
  onClick?: () => void;
}
function UserCard({ name, onClick }: UserCardProps) { /* ... */ }
Real-world example
Migrating a legacy React component library from runtime PropTypes validation to compile-time TypeScript prop types.
Likely follow-ups
  • What capability does PropTypes retain that pure compile-time TypeScript types lose, given TypeScript types don't exist at runtime?
Related topics