20
What is the difference between TypeScript and PropTypes
If you've been working with React for a while, you probably heard about the term PropTypes.
PropTypes helps us check if the props we are passing to our components are in the type we expect them to be(string, number, object, etc.).
export function DisplayTitle({ title = 'Hello' }) {
return (
<div>
<H2>{title}</H2>
</div>
);
}
DisplayTitle.propTypes = {
title: PropTypes.string.isRequired
};
We can perform the same action with TypeScript using an Interface or a Type.
export type DisplayTitleProps = {
title: string
};
export function DisplayTitle({ title = 'Hello' }: DisplayTitleProps) {
return (
<div>
<H2>{title}</H2>
</div>
);
}
One might think that PropTypes was invented to serve the poor JavaScript developers. "At least let them have their props typed!".
But there is a significant difference between typing our props with PropTypes and TypeScript.
TypeScript checks for errors in the compilation process. While generating the JavaScript files, TS will check for any errors. TS will cancel the compilation process and yield an error if any are found.
PropTypes, however, checks for errors on runtime. Your prop types will be checked when you run your app in the browser. If anything is wrong, an error in the console will appear:
Warning: Failed prop type: Invalid prop `id` of type `string` supplied to `sum,` expected `number.`
When will we prefer using PropTypes over TypsScript for our props?
A typical use case for preferring PropTypes over TypeScript is receiving data from a server. TypeScript has no way to find out if the data we receive from the server is in the type we expect it to be (unless you're getting the data on build time when statically building the site).
For such a case, we will have to use PropTypes to check that the data we get from the server is in the correct type.
There is another solution, however. You can create a "Type component" using Bit. Now that your Types are components, you can install them in both the backend and the frontend. By doing so, we prevent the possibility of getting the wrong type of (without having to type-check on runtime).
Another great advantage with this method is that now we have only a single source of truth. Every time we want to add a property, we update the Type component. After updating our component, we can install the new version in the back and frontend, and we're all set!
For more posts like this follow me on LinkedIn
I work as frontend & content developer for Bit - a toolchain for component-driven development (Forget monolithic apps and distribute to component-driven software).
20