This short and practical guide will remind you of the TypeScript essentials every React developer should know. Perfect for interviews, daily development, or converting a JS app to TypeScript.
Why Use TypeScript?
TypeScript adds static typing to JavaScript. Benefits:
- Prevents runtime bugs with compile-time checks
- Improves code autocomplete and documentation
- Enforces better architecture
Type Basics
let count: number = 0;
let name: string = "Alice";
let isLoggedIn: boolean = true;
let tags: string[] = ["react", "typescript"];
Interfaces and Types
Use interface
or type
to define shape of objects.
interface User {
id: number;
name: string;
}
type Product = {
id: string;
price: number;
}
Props in React Components
type ButtonProps = {
label: string;
onClick: () => void;
}
function Button({ label, onClick }: ButtonProps) {
return <button onClick={onClick}>{label}</button>;
}
With interface:
interface UserCardProps {
name: string;
age?: number; // optional prop
}
useState with Types
const [count, setCount] = useState<number>(0);
const [user, setUser] = useState<User | null>(null);
useReducer with Types
type Action = { type: 'increment' } | { type: 'decrement' };
const reducer = (state: number, action: Action): number => {
switch (action.type) {
case 'increment': return state + 1;
case 'decrement': return state - 1;
}
};
const [count, dispatch] = useReducer(reducer, 0);
Custom Hooks with Types
function useToggle(initial: boolean): [boolean, () => void] {
const [value, setValue] = useState(initial);
const toggle = () => setValue((v) => !v);
return [value, toggle];
}
Typing API Data
type Post = {
id: number;
title: string;
}
async function fetchPosts(): Promise<Post[]> {
const res = await fetch('/api/posts');
return res.json();
}
TypeScript in Redux Toolkit
interface CounterState {
value: number;
}
const initialState: CounterState = { value: 0 };
const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment(state) { state.value += 1; }
}
});
Utility Types
-
Partial<T>
– All properties optional -
Pick<T, K>
– Subset of properties -
Omit<T, K>
– All but specified properties -
Record<K, T>
– Object type with fixed keys -
Readonly<T>
– Makes all props immutable
Example:
type UserPreview = Pick<User, 'id' | 'name'>;
TypeScript + React Diagram
Component Props
↓
[ TS Interface/Type ]
↓
Typed React Component
↓
useState<T>, useReducer<T>
↓
Fully typed component behavior
Summary
- Use
type
orinterface
to define structure - Annotate props and hook return types
- Use
TS + React
for safe, scalable code - Combine with Redux Toolkit for powerful typed state management
Top comments (0)