React và TypeScript là cặp đôi phổ biến nhất ở frontend hiện nay. Bài này không dạy React từ đầu — nó chỉ ra chỗ nào cần kiểu và cách viết gọn nhất. Tạo dự án mẫu:
npm create vite@latest my-shop -- --template react-tstype là đủtype ProductCardProps = {
name: string;
price: number;
onSale?: boolean;
onAddToCart: (sku: string) => void;
children?: React.ReactNode;
};
export function ProductCard({ name, price, onSale = false, onAddToCart, children }: ProductCardProps) {
return (
<article>
<h3>{name}</h3>
<p>{price.toLocaleString("vi-VN")} ₫ {onSale && "🔥"}</p>
{children}
<button onClick={() => onAddToCart(name)}>Thêm vào giỏ</button>
</article>
);
}React.FC.React.ReactNode là kiểu cho bất cứ thứ gì render được: chuỗi, số, element, mảng, null.onAddToCart hay truyền price="100" → lỗi compile ngay trong JSX.Muốn component Button nhận mọi thuộc tính của <button> (disabled, type, aria-*...)?
type ButtonProps = React.ComponentProps<"button"> & {
variant?: "primary" | "ghost";
};
export function Button({ variant = "primary", className, ...rest }: ButtonProps) {
useState suy ra kiểu từ giá trị đầu. Khi giá trị đầu chưa đủ thông tin, truyền generic:
const [count, setCount] = useState(0); // number
const [user, setUser] = useState<User | null>(null); // User | null
const inputRef = useRef<HTMLInputElement>(null
Rê chuột lên onChange trong editor để biết kiểu, hoặc nhớ vài kiểu hay dùng:
function SearchBox({ onSearch }: { onSearch: (q: string) => void }) {
const [q, setQ] = useState("");
const handleChange = (e: React.
Khi viết handler inline (onChange={(e) => setQ(e.target.value)}), kiểu của e được suy ra tự động.
Đây là nơi kiến thức chương 4 tỏa sáng:
type CartAction =
| { type: "add"; sku: string; price: number }
| { type: "remove"; sku: string }
| { type: "clear" };
type
Component cũng là hàm, nên có thể generic:
type ListProps<T> = {
items: T[];
getKey: (item: T) => string;
renderItem: (item: T) => React.ReactNode;
};
undefinedconst AuthContext = createContext<{ user: User; logout: () => void } | null>(null);
export function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) throw
TIP
Dữ liệu từ API vẫn là dữ liệu ngoài: parse response bằng schema (chương 10) trước khi đưa vào state. Các thư viện fetch dữ liệu phổ biến đều nhận generic hoặc schema để gắn kiểu cho kết quả.
Comments