TypeScript: The good parts — 1. React Prop-types
React Components tend to be designed with the idea of reuse and composition. Being able to describe the input interface to components is of great value.
Let us consider the following CardLayout component.
Option 1. Prop Types
Your code will look like this:
import PropTypes from 'prop-types';function CardLayout({ title, details, imageUrl }) {
return (
<Card>
<CardThumbNail>
<CardThumbNailImage src={imageUrl} />
</CardThumbNail>
<CardTitle>{title}</CardTitle>
<CardDetail>{details}</CardDetail>
</Card>
);
}CardLayout.propTypes = {
title: PropTypes.string,
details: PropTypes.string,
imageUrl: PropTypes.string
};
Pros:
You get prop types check at runtime.
Cons:
- You must install prop-types via:
npm install --save prop-types
2. The usage seems like an after thought. It is a kind of monkey-patch.
Option 2: TypeScript interfaces
interface ICardProps {
title: string;
details: string;
imageUrl: string;
}function CardLayout({ title, details, imageUrl }: ICardProps) {
return (
<Card>
<CardThumbNail>
<CardThumbNailImage src={imageUrl} />
</CardThumbNail>
<CardTitle>{title}</CardTitle>
<CardDetail>{details}</CardDetail>
</Card>
);
}
There are no cons to this approach. The code communicates pretty well. The interface definition should provide enough confidence in using the component.
Some might want to push it another step further with:
const CardLayout: FunctionComponent<ICardProps> = function({ title, details, imageUrl }) { ....
However, I believe that having to specify CardLayout as a Functional Component is redundant. It doesn’t really add any extra information. If your file is named CardLayout.tsx, it is quite clear what the purpose of the function is.
I have a gut feeling that TypeScript basic types and interfaces is all you need in a typical React application. If you check out my previous article, you’ll see my approach to typing. Use just where you need it. Typing for typing sake is just noise.