How to set up React with TypeScript from scratch
· Category: React
Short answer
You can scaffold a React TypeScript project with Vite or Create React App, then type components, props, events, and hooks for compile-time safety.
Steps
- Run
npm create vite@latest my-app -- --template react-ts. - Define props as interfaces or type aliases.
- Type event handlers with
React.MouseEvent,React.ChangeEvent, etc. - Use generics for custom hooks and polymorphic components.
Example
interface ButtonProps {
label: string;
onClick: () => void;
}
const Button: React.FC<ButtonProps> = ({ label, onClick }) => (
<button onClick={onClick}>{label}</button>
);
Tips
- Enable strict mode in
tsconfig.jsonfor maximum safety. - Use
React.Nodefor children andReact.ElementTypefor polymorphicasprops. - Avoid
any; preferunknownwith type narrowing.