How do I use TypeScript with React to avoid bugs?

RI ricardo84 BR 🔍 Enthusiast 👁 75 ⚑ Report Programming

I'm developing a React project here and decided to try TypeScript to see if it really does improve things. But I'm finding it pretty confusing to integrate types with components, hooks and props. Does anyone who already uses it have a tip on how to get started without getting too lost?

2 answers

★ Best answer

The trick is to start by typing your component props with `interface` or `type`, like `interface Props { name: string; age: number; }` and then use that in your component `function Comp({ name, age }: Props)`. For hooks, TypeScript already infers a lot on its own (if you use `useState(0)`, it knows it's a number), but when you've got a more complex object then you type it manually: `const [user, setUser] = useState<{ name: string; email: string } | null>(null)`. Start with that, let the rest come gradually - don't try to type everything at once or it'll turn into a mess.

Start by typing your props with `interface`, but the real trick is using `React.FC<Props>` or even better just `function Comp(props: Props)` so you don't get confused with children typing. What trips a lot of people up is trying to type everything from day one - focus on props and state first, let TypeScript infer types in places where it figures them out on its own, otherwise you end up feeling like you're fighting the language instead of having it work for you.

Your answer

Log into answer.