UrbanCart's ProductCard crashes because someone passed a string where a number was expected. TypeScript stops that before the code even runs.
๐ท TypeScriptโ๏ธ React๐ท๏ธ Props Typing๐ก Intermediate๐ ~22 min
Lesson 37 of Full Stack Track
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.tsxProps 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.tsxuseState 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.tsxReact.ChangeEvent โ UrbanCart
LoginForm.tsxReact.FormEvent โ UrbanCart
AddToCartButton.tsxReact.MouseEvent โ UrbanCart
Common React Event Types
Event
Type
Element
onChange
React.ChangeEvent<HTMLInputElement>
input, textarea
onSubmit
React.FormEvent<HTMLFormElement>
form
onClick
React.MouseEvent<HTMLButtonElement>
button, div
onKeyDown
React.KeyboardEvent<HTMLInputElement>
input, div
onFocus / onBlur
React.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.tsxuseRef 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.tsxGeneric 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.tsxFull 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.tsCustom 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
11. Try It Yourself โ Typed SearchInput with React.ChangeEvent
This editor shows how React.ChangeEvent<HTMLInputElement> types the event in a search filter. The handleChange function is extracted (not inline) to make the type annotation visible. Edit the product list or try changing the handler signature.
Try It Yourself โ Typed Search & Filter
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?