TypeScript for React Developers Series: Why You Should Adopt It
TypeScript is a superset of JavaScript that adds static typing, which makes your code readable, maintainable and re-usable.
when you adopt TypeScript to React projects, you don't need to add additional packages to validate props like prop-types
, also you can catching types errors in compile-time rather than runtime, and getting IntelliSense to your IDE, which can help you to write code quickly and correctly.
Prerequisites:
- Basics of React.js
The freedom of JavaScript can be painful when you work in a team, when you don't write tests for your application, and when application grows.
Imagine you have a component that accepts 'position' as a prop, this prop will be 'left' or 'right' to work well, with JavaScript you need to add a manual check
//components/MyComponent.jsx
function MyComponent({ position = "left" }) {
if (position === "left") {
return <div>left</div>;
}
if (position === "right") {
return <div>right</div>;
}
return <div>position will be right or left</div>;
}
//App.js
import MyComponent from "./components/MyComponent";
function App() {
return (
<div className="App">
<MyComponent position="fddffd" />
</div>
);
}
export default App;
you can use the prop-types
to validate the props but it is still painful :
//components/MyComponent.jsx
import React from "react";
import PropTypes from "prop-types";
function MyComponent({ position = "left" }) {
if (position === "left") {
return <div>left</div>;
}
if (position === "right") {
return <div>right</div>;
}
return <div>position will be right or left</div>;
}
MyComponent.propTypes = {
position: PropTypes.oneOf(["right", "left"]),
};
export default MyComponent;
//App.js
import MyComponent from "./components/MyComponent";
function App() {
return (
<div className="App">
<MyComponent position="fddffd" />
</div>
);
}
export default App;
No warning or alert again 🥲:
To make sure is props are valid you must open the console to show up the errors and warnings:
But when we use TypeScript you will get alerts and warnings anywhere :
//components/MyComponent.tsx
interface MyComponentProps {
position: "right" | "left";
}
function MyComponent({ position }: MyComponentProps) {
return <div>{position}</div>;
}
export default MyComponent;
Your IDE tells you stop you have error 🛑
Also your browser gives you alerts to correct your code
conclusion:
TypeScript is a powerful tool that helps you to become a productive developer and to write clean and readable code, it's not just a props validator, we can do with it a lot of things like alias
, creating solid and re-usable components with generics