Vấn đề thường gặp là gõ any cho event hoặc đoán sai kiểu element.
Event handlers — React có sẵn type generic theo element và loại event. Lấy đúng kiểu thay vì any:
tsx
const onClick = (e: React.MouseEvent<HTMLButtonElement>) => {}
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log(e.target.value) // value được type đúng
}
const onSubmit = (e: React.FormEvent<HTMLFormElement>) => e.preventDefault()Mẹo: khai báo handler inline trên JSX prop thì TS tự suy ra type của e — chỉ cần annotate khi tách hàm ra ngoài.
Refs — type theo element được gắn, khởi tạo null:
tsx
const inputRef = useRef<HTMLInputElement>(null)
// inputRef.current là HTMLInputElement | null → phải guard
inputRef.current?.focus()Lưu ý: useRef<T>(null) cho ref DOM tạo ra ref read-only (RefObject), đúng cho việc gắn vào JSX.
- Còn
useRef<T>(initial)cho "instance variable" mutable thì khởi tạo bằng giá trị thật, không phảinull. - Phân biệt hai cái này để tránh lỗi type "current is read-only".