1. Why Type React Components

JavaScript lets you pass anything to a component โ€” a string, a number, undefined, even another component. That freedom causes real bugs in production. TypeScript adds a compile-time safety net so your editor catches mistakes as you type, not after the customer sees a broken screen.

๐Ÿ›’
UrbanCart Example
The price bug that TypeScript prevents

Imagine ProductCard receives a price prop. A developer accidentally passes price="49.99" (a string) instead of price={49.99} (a number). The component tries to do price * 0.9 for the discount โ€” and renders NaN. With TypeScript, this error appears in the editor the moment you write it, before any browser is involved.

โŒ

Without TypeScript

Mistakes surface at runtime, in production, when real customers see them. No warning, no help from the editor.

โœ…

With TypeScript

Wrong prop types, missing required props, and null dereferences are flagged in your editor immediately โ€” zero guesswork.

How it works in practice: TypeScript is a superset of JavaScript โ€” all valid JS is valid TS. You add type annotations where helpful, and the compiler strips them before the browser runs the code. In React, the main places you add types are: props, state, event handlers, and refs.

2. Typing Props

The most common TypeScript pattern in React is defining an interface for a component's props, then using it as the parameter type. This gives you autocomplete, inline documentation, and compile-time errors for missing or wrong props.

ProductCard.tsx Props interface โ€” UrbanCart
Interface vs type alias: You can also use type ProductCardProps = { ... }. Both work for props. The convention in React is to prefer interface for object shapes because it gives cleaner error messages, but either is fine.
๐Ÿท๏ธ
Pattern note
Children and ReactNode

If your component wraps other components (like a Card layout), add children: React.ReactNode to your interface. ReactNode covers JSX, strings, numbers, arrays โ€” anything React can render.

Card.tsxTyping children

3. Typing State

TypeScript can usually infer the type of state from the initial value. useState(0) gives you number, useState('') gives you string. But when the initial value is an empty array or null, you need to be explicit with a generic.

Cart.tsx useState generics โ€” UrbanCart
When to use generics with useState
useState([]) โ†’ infers never[] โ€” ALWAYS add generic: useState<Product[]>([]) useState(null) โ†’ infers null only โ€” add union: useState<string | null>(null) useState(0) โ†’ infers number โœ… โ€” no generic needed useState('') โ†’ infers string โœ… โ€” no generic needed useState(false) โ†’ infers boolean โœ… โ€” no generic needed useState({ name: '' }) โ†’ infers shape โœ… โ€” but explicit interface is cleaner

4. Typing Events

React wraps native DOM events in its own type system. When you write an event handler inline, TypeScript infers the type automatically. When you extract the handler to a separate function, you need to annotate it explicitly.

SearchInput.tsx React.ChangeEvent โ€” UrbanCart
LoginForm.tsx React.FormEvent โ€” UrbanCart
AddToCartButton.tsx React.MouseEvent โ€” UrbanCart
Common React Event Types
Event Type Element
onChangeReact.ChangeEvent<HTMLInputElement>input, textarea
onSubmitReact.FormEvent<HTMLFormElement>form
onClickReact.MouseEvent<HTMLButtonElement>button, div
onKeyDownReact.KeyboardEvent<HTMLInputElement>input, div
onFocus / onBlurReact.FocusEvent<HTMLInputElement>input, textarea

5. Typing Refs

useRef in TypeScript requires a generic so that ref.current has the right type. Without the generic, ref.current is unknown and you can't call any DOM methods on it.

SearchBar.tsx useRef with HTMLInputElement โ€” UrbanCart
Why null as initial value? The ref starts as null because the DOM element doesn't exist until after the first render. After React mounts the component, ref.current points to the real DOM node. The optional chaining ?. pattern (ref.current?.focus()) safely handles the brief moment it's still null.

6. Generic Components

Sometimes you want a component that works with any data type โ€” a generic list, a dropdown, a table. TypeScript generics let you write one component that stays fully typed no matter what data you pass.

List.tsx Generic component โ€” UrbanCart
Key insight: The generic T flows from the items array to the render callback โ€” TypeScript connects them. When you use <List items={products} ... />, TypeScript knows the product argument in render is a Product, so you get full autocomplete inside the callback.

7. Typing Context

Context in TypeScript requires you to type both the shape of the value and handle the fact that the context starts as null (before a Provider wraps the component). The standard pattern uses a non-null assertion inside a custom hook.

CartContext.tsx Full typed context โ€” UrbanCart
Why CartContextType | null? createContext needs an initial value. Before any <CartProvider> wraps your component, the context is null. Typing it as | null makes TypeScript aware of this so you're forced to check โ€” which the useCart hook does for you in one place.

8. Typing Custom Hooks

Custom hooks are just functions, so TypeScript handles them naturally. Most of the time the return type is inferred automatically. But annotating it explicitly makes your hook's contract clear and catches mismatches early.

useProducts.ts Custom hook with return type annotation โ€” UrbanCart
Inferred vs explicit: TypeScript can usually infer the return type of a hook from its return statement. The benefit of annotating it explicitly is that you get an error inside the hook if you accidentally return the wrong shape โ€” rather than a confusing error at the call site.

9. Before / After โ€” JS โ†’ TS Conversion

Migrating a component from JavaScript to TypeScript is mostly about adding interfaces and type annotations. Here is the same ProductCard component before and after.

BEFORE โ€” JavaScript
AFTER โ€” TypeScript
Migration tip: You don't have to migrate a whole codebase at once. Rename .jsx to .tsx one file at a time. Start with the smallest, most reused components (like Button, ProductCard) so you get the most benefit fastest.

10. Try It Yourself โ€” Typed ProductCard

This editor runs TypeScript-flavored React via Babel standalone. Babel strips the type annotations before running the code, so you see the live output. In a real project the TypeScript compiler would flag type errors โ€” here, focus on reading the pattern.

How this works: Babel standalone in the browser compiles TypeScript syntax to plain JavaScript. It does not enforce types (that's what tsc does in a real project), but the code runs exactly as it would after compilation. Try changing price={49.99} to price="free" to see what would have happened without types.
Try It Yourself โ€” Typed ProductCard
Preview

Quiz

Question 1 of 5
How do you type a React component's props in TypeScript?
Question 2 of 5
What type should you use for an onChange event handler on an <input> element?
Question 3 of 5
How do you type useState that holds an array of products?
Question 4 of 5
What does useRef<HTMLInputElement>(null) do?
Question 5 of 5
What is the primary benefit of using TypeScript with React?
0
/ 5
Great job!

You completed the TypeScript with React quiz.

Next Lesson

TypeScript with Node & Next.js โ†’
Arc F continues: bring TypeScript into the backend and full-stack Next.js.
Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

You can now type every part of a React app.
Let's turn that into a full-stack career.

Join the Best AI Programs โ€” three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses โ†’