TypeScript cho React
Đặt kiểu cho props, state, sự kiện, ref, context; generic component; props loại trừ nhau bằng union; kế thừa props của thẻ HTML; polymorphic as.
Gần như mọi dự án React chuyên nghiệp dùng TypeScript. Kiểu tốt không chỉ bắt lỗi đánh máy — nó làm cho trạng thái sai không thể viết ra được và biến component thành tài liệu sống cho cả team.
🎯 Mục tiêu học tập
- Khai báo kiểu props, children, event handler, ref
- Kế thừa thuộc tính của thẻ HTML gốc bằng
ComponentProps - Viết generic component (
<List<T>>,<Select<T>>) - Dùng discriminated union cho props loại trừ nhau
- Cấu hình
strictvà các cờ nên bật
Props, children và sự kiện
type ButtonProps = {
variant?: 'primary' | 'secondary' | 'ghost';
loading?: boolean;
children: React.ReactNode; // bất kỳ thứ gì render được
onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void;
};
export function Button({ variant = 'primary', loading = false, children, onClick }: ButtonProps) {
return <button className={`btn btn-${variant}`} disabled={loading} onClick={onClick}>{children}</button>;
}
function Search() {
const [q, setQ] = useState(''); // suy kiểu: string
const [user, setUser] = useState<User | null>(null); // cần khai báo khi giá trị đầu là null
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => setQ(e.target.value);
const inputRef = useRef<HTMLInputElement>(null);
return <input ref={inputRef} value={q} onChange={onChange} />;
}
Kế thừa props của thẻ HTML
type InputProps = React.ComponentProps<'input'> & { // có sẵn value, onChange, placeholder, aria-*, ref...
label: string;
error?: string;
};
export function TextField({ label, error, id, ...rest }: InputProps) {
const autoId = useId();
const inputId = id ?? autoId;
return (
<div>
<label htmlFor={inputId}>{label}</label>
<input id={inputId} aria-invalid={!!error} aria-describedby={error ? `${inputId}-err` : undefined} {...rest} />
{error && <p id={`${inputId}-err`}>{error}</p>}
</div>
);
}
// Lấy props của một component khác
type CardProps = React.ComponentProps<typeof Card>;
Generic component
type ListProps<T> = {
items: T[];
getKey: (item: T) => string | number;
renderItem: (item: T) => React.ReactNode;
empty?: React.ReactNode;
};
export function List<T>({ items, getKey, renderItem, empty = 'Trống' }: ListProps<T>) {
if (items.length === 0) return <p>{empty}</p>;
return <ul>{items.map(i => <li key={getKey(i)}>{renderItem(i)}</li>)}</ul>;
}
// T được suy ra là Product -> renderItem có gợi ý p.name, p.price
<List items={products} getKey={p => p.id} renderItem={p => `${p.name} - ${p.price}`} />
Props loại trừ nhau
// Link HOẶC button, không bao giờ cả hai
type ActionProps =
| ({ as: 'link'; href: string } & Omit<React.ComponentProps<'a'>, 'href'>)
| ({ as: 'button'; href?: never } & React.ComponentProps<'button'>);
function Action(props: ActionProps) {
if (props.as === 'link') {
const { as, ...rest } = props;
return <a {...rest} />;
}
const { as, ...rest } = props;
return <button {...rest} />;
}
// Modal: nếu có onConfirm thì bắt buộc có confirmText
type ModalProps = { title: string } & (
| { onConfirm: () => void; confirmText: string }
| { onConfirm?: undefined; confirmText?: undefined }
);
Context có kiểu và cấu hình nên bật
const AuthContext = createContext<AuthValue | null>(null);
export const useAuth = () => {
const v = useContext(AuthContext);
if (!v) throw new Error('Thiếu AuthProvider');
return v; // kiểu AuthValue, không còn null
};
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitOverride": true,
"jsx": "react-jsx",
"moduleResolution": "bundler",
"verbatimModuleSyntax": true
}
}
Kiểu dữ liệu từ API không đáng tin (server có thể trả sai). Validate ở biên bằng Zod: const user = UserSchema.parse(await res.json())
rồi suy kiểu type User = z.infer<typeof UserSchema> — một nguồn sự thật cho cả kiểu và validate.
🚩 Sai lầm hay gặp
- Dùng
React.FCcho mọi component — không sai, nhưng khai báo props trực tiếp rõ và linh hoạt hơn (generic dễ hơn). - Rải
as any/!để 'qua mặt' lỗi — mỗi chỗ là một bug tiềm năng. - Tin kiểu của
res.json()mà không validate.
🏋️ Bài tập thực hành
Chuyển Todo app, giỏ hàng, thư viện hook sang TS strict + noUncheckedIndexedAccess. Viết DataTable<T> generic có cột cấu hình được, sắp xếp theo cột với kiểu an toàn (keyof T). Không dùng any.
📚 Tài nguyên học tập
-
React TypeScript CheatsheetTra cứu nhanhDocs
-
react.dev — Using TypeScriptHướng dẫn chính thứcDocs
-
ZodValidate + suy kiểuLibrary
✅ Tự đánh giá hoàn thành
- Tôi đặt kiểu được cho props, event, ref, context
- Tôi viết được generic component
- Tôi dùng union để ngăn tổ hợp props không hợp lệ
- Tôi validate dữ liệu API bằng Zod