7 min read
Mastering TypeScript for React Developers
TypeScriptReactJavaScriptType Safety
Mastering TypeScript for React Developers
TypeScript has become an essential tool for React developers who want to build more robust and maintainable applications. In this post, we'll explore advanced TypeScript patterns specifically tailored for React development.
Type-Safe Component Props
One of the most important aspects of TypeScript in React is properly typing your component props:
interface ButtonProps {
variant: 'primary' | 'secondary' | 'danger';
size?: 'small' | 'medium' | 'large';
disabled?: boolean;
onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
children: React.ReactNode;
}
const Button: React.FC<ButtonProps> = ({
variant,
size = 'medium',
disabled = false,
onClick,
children
}) => {
return (
<button
className={`btn btn-${variant} btn-${size}`}
disabled={disabled}
onClick={onClick}
>
{children}
</button>
);
};
Generic Components
Generic components allow you to create reusable components that work with different data types:
interface ListProps<T> {
items: T[];
renderItem: (item: T, index: number) => React.ReactNode;
keyExtractor: (item: T) => string | number;
}
function List<T>({ items, renderItem, keyExtractor }: ListProps<T>) {
return (
<ul>
{items.map((item, index) => (
<li key={keyExtractor(item)}>
{renderItem(item, index)}
</li>
))}
</ul>
);
}
Conclusion
TypeScript and React make a powerful combination when used correctly. By leveraging TypeScript's type system, you can catch errors early, improve code maintainability, and enhance the developer experience.
Written by Vũ Thanh Thiên