Why I Switched to TypeScript for React (And You Should Too)
I resisted TypeScript for a long time. "Why do I want to write more code to do the same thing?" I thought. "JavaScript gives me freedom!"
Then I worked on a large React codebase with three other developers. I spent hours debugging why a component was breaking, only to realize someone passed a string "10" instead of the number 10.
JavaScript's "freedom" is also its chaos. TypeScript brings order.
What is TypeScript?
TypeScript is a "superset" of JavaScript. This means all valid JavaScript is valid TypeScript. You can rename a .js file to .ts and it will mostly work. The difference is that TypeScript adds Static Typing.
The React Prop Problem
In standard React, we often guess what props a component needs. We might use PropTypes, but those only warn you in the browser console after the app runs.
JavaScript:
const UserCard = ({ user }) => {
return <h1>{user.nmae}</h1> // Typo! It should be 'name'
}
// JS won't catch this until the browser renders "undefined"
TypeScript:
interface User {
id: number;
name: string;
email?: string; // Optional
}
interface Props {
user: User;
}
const UserCard = ({ user }: Props) => {
return <h1>{user.nmae}</h1>
// ERROR: Property 'nmae' does not exist on type 'User'. Did you mean 'name'?
}
TypeScript screams at you in your code editor (VS Code) before you even save the file.
Refactoring with Confidence
Imagine you want to rename user.name to user.fullName across an app with 50 components.
- In JavaScript: You do "Find and Replace" and pray you didn't break anything. You manually test every page.
- In TypeScript: You rename the property in the
interface. TypeScript immediately highlights every single file in your project where that property is used, marking them with red squiggly lines. You fix them, and you know the app is safe.
How to Migrate a React Project
You don't have to rewrite your whole app overnight. You can adopt TypeScript incrementally.
- Install TS:
npm install typescript @types/react @types/node - Rename files: Change
Footer.jstoFooter.tsx. - Fix errors: Add basic types (or use
anyas a temporary escape hatch). - Repeat: Do this one component at a time.
Conclusion
TypeScript does require a bit more typing upfront, but it pays for itself ten times over in debugging time saved. It acts as self-documentation; looking at the Interface tells you exactly what a component needs to work.
Once you go TypeScript, you never go back.