How to use TypeScript with React
· Category: TypeScript
Short answer
Create a React app with TypeScript using npx create-react-app my-app --template typescript or Vite. Type props with interfaces and hooks with generics. For improving frontend performance, see how to improve core web vitals. For understanding component patterns, see python classes objects.
Steps
- Bootstrap:
npm create vite@latest my-app -- --template react-ts - Define props:
interface ButtonProps { label: string; onClick: () => void; } - Type state:
const [count, setCount] = useState<number>(0) - Type events:
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {} - Run type checking:
npx tsc --noEmit
Tips
- Use
React.FCsparingly; explicit props interfaces are preferred - Type ref callbacks with
React.RefCallback<HTMLInputElement> - For package management, see python pip install packages