Typing React components
How to type React components with React 19's types: props, children and defaults, event handlers, useState, useRef and useReducer, wrappers around native elements that take ref as a prop, generic components, and props that only make sense in certain combinations.
Reading level
Shows sections up to the selected level.
This topic starts at Junior level.
Typing props and children
Komponentin props-u bir obyektdir, ona görə onu istənilən obyekt kimi tipləyirsən: type alias və ya interface yazırsan və parametrə annotasiya qoyursan. Bundan sonra TypeScript komponentin istifadə olunduğu hər yeri yoxlayır. JSX atributları obyekt literalının xassələri kimi yoxlanır, ona görə çatışmayan, səhv yazılmış və ya tipi uyğun gəlməyən prop kompilyasiya xətası verir.
type BadgeProps = {
label: string;
tone?: "neutral" | "success" | "danger";
count?: number;
};
function Badge({ label, tone = "neutral", count }: BadgeProps) {
return (
<span className={`badge badge-${tone}`}>
{label}
{count !== undefined && <b>{count}</b>}
</span>
);
}
<Badge label="New" />;
// Xəta: 'label' xassəsi yoxdur
<Badge />;
// Xəta: "warn" tone dəyərlərindən biri deyil
<Badge label="New" tone="warn" />;
// Xəta: BadgeProps-da 'colour' yoxdur
<Badge label="New" colour="red" />;? prop-u məcburi olmayan (optional) edir. Komponentin içində onun tipinə undefined da daxil olur (count number | undefined-dir), ona görə TypeScript prop-un verilmədiyi halı da nəzərə almağa məcbur edir. Destructuring-dəki default dəyər undefined-i aradan qaldırır: yuxarıdakı tone sadəcə union-dır. React 19 funksiya komponentləri üçün defaultProps-u ləğv edib, ona görə default dəyərlər destructuring-də verilir. Default yalnız dəyər undefined olanda işləyir; null kimi ötürülən prop isə null qalır.
Props üçün həm type, həm də interface yararlıdır; kod bazası üçün birini seç. Qaytarılan tipi nadir hallarda yazırsan: TypeScript onu özü . React.FC<Props> də məcburi deyil. O, funksiyanı tipləyir, amma React 18 tiplərindən bəri props-a children əlavə etmir.
children
children adi prop-dur və onu özün yazırsan. Adətən onun tipi ReactNode-dur: React-in render edə bildiyi hər şey, məsələn, elementlər, sətirlər, ədədlər, boolean-lar, null, undefined və bunlardan ibarət massivlər.
import type { ReactNode } from "react";
type CardProps = {
title: string;
children: ReactNode;
};
function Card({ title, children }: CardProps) {
return (
<section>
<h2>{title}</h2>
{children}
</section>
);
}ReactElement daha dardır: yalnız JSX elementləri, ona görə onunla <Card>Text</Card> xəta verərdi. Heç biri "yalnız <li> elementləri" deyə bilməz: react.dev qeyd edir ki, TypeScript children-i müəyyən növ JSX elementi kimi təsvir edə bilmir. PropsWithChildren<P> P-yə məcburi olmayan children?: ReactNode əlavə edir, style prop-u isə React.CSSProperties qəbul edir.
A component's props are one object, so you type them like any object: a type alias or an interface, and an annotation on the parameter. From then on TypeScript checks every place the component is used. JSX attributes are checked like the properties of an object literal, so a missing, misspelled or wrongly typed prop is a compile error.
type BadgeProps = {
label: string;
tone?: "neutral" | "success" | "danger";
count?: number;
};
function Badge({ label, tone = "neutral", count }: BadgeProps) {
return (
<span className={`badge badge-${tone}`}>
{label}
{count !== undefined && <b>{count}</b>}
</span>
);
}
<Badge label="New" />;
// Error: property 'label' is missing
<Badge />;
// Error: "warn" is not one of the tones
<Badge label="New" tone="warn" />;
// Error: 'colour' does not exist in BadgeProps
<Badge label="New" colour="red" />;A ? makes a prop optional. Inside the component its type then includes undefined (count is number | undefined), so TypeScript makes you handle the missing case. A default value in the destructuring removes undefined: tone above is just the union. React 19 removed defaultProps for function components, so destructuring defaults are the way to set them. A default applies only when the value is undefined; a prop passed as null stays null.
type or interface both work for props; pick one convention for the codebase. You rarely write the return type: TypeScript it. React.FC<Props> is optional too. It types the function, but since the React 18 types it does not add children to the props.
children
children is an ordinary prop, and you list it yourself. Its usual type is ReactNode: everything React can render, such as elements, strings, numbers, booleans, null, undefined and arrays of these.
import type { ReactNode } from "react";
type CardProps = {
title: string;
children: ReactNode;
};
function Card({ title, children }: CardProps) {
return (
<section>
<h2>{title}</h2>
{children}
</section>
);
}ReactElement is narrower: JSX elements only, so <Card>Text</Card> would fail with it. Neither can say "only <li> elements": react.dev notes that TypeScript cannot describe children as a certain type of JSX element. PropsWithChildren<P> adds an optional children?: ReactNode to P, and a style prop takes React.CSSProperties.
Typing event handlers
Handler-i inline yazanda event-in tipini ümumiyyətlə yazmırsan: TypeScript <input>-un onChange prop-unun tipini bilir və onu parametrə verir.
function TaskTitle() {
const [title, setTitle] = useState("");
// e: React.ChangeEvent<HTMLInputElement>
return <input value={title} onChange={(e) => setTitle(e.target.value)} />;
}Handler-i adlı funksiyaya çıxaranda bu kontekst itir. strict rejimində tipsiz parametr implicit any xətası verir, ona görə ona annotasiya yazırsan. react.dev-in məsləhəti: redaktorda kursoru prop-un (onChange) üzərinə gətir və onun hansı event tipini gözlədiyinə bax.
function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
console.log(event.target.value);
}
// və ya bütün funksiyanı handler tipi ilə tiplə
const handleKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (event) => {
if (event.key === "Escape") event.currentTarget.blur();
};Gündəlik işdə ən çox lazım olanlar ChangeEvent (input, select, textarea), MouseEvent, KeyboardEvent və FocusEvent-dir. onSubmit üçün cari tiplər SubmitEvent<HTMLFormElement> istifadə edir; köhnə FormEvent hələ kompilyasiya olunur, amma deprecated kimi işarələnib. Tip parametri handler-in bağlandığı elementdir. Bunlar React-in tipləridir: onları react-dən import et və ya React.MouseEvent yaz. Sadəcə MouseEvent DOM-un öz tipidir və onunla tiplənmiş handler onClick-ə uyğun gəlmir.
target, yoxsa currentTarget
currentTarget handler-in bağlandığı elementdir və məhz o elementin tipini daşıyır. target isə event-in başladığı yerdir, bu, uşaq element də ola bilər, ona görə klikdə onun tipi sadəcə EventTarget-dir:
function handleClick(event: React.MouseEvent<HTMLButtonElement>) {
// Xəta: 'EventTarget' tipində 'disabled' yoxdur
event.target.disabled = true;
event.currentTarget.disabled = true;
}Change event-ləri istisnadır: onların target-i form elementi kimi tiplənib, ona görə onChange-də e.target.value işləyir. Digər hallarda event.target as HTMLButtonElement kimi cast əvəzinə currentTarget-dən istifadə et.
Callback props
Komponentin öz event prop-ları DOM event-lərini yox, dəyərləri ötürməlidir. AddTaskForm-un valideyninə başlıq lazımdır:
type AddTaskFormProps = {
onAdd: (title: string) => void;
};
function AddTaskForm({ onAdd }: AddTaskFormProps) {
const [title, setTitle] = useState("");
function handleSubmit(event: React.SubmitEvent<HTMLFormElement>) {
event.preventDefault();
onAdd(title.trim());
setTitle("");
}
return (
<form onSubmit={handleSubmit}>
<input value={title} onChange={(e) => setTitle(e.target.value)} />
<button type="submit">Add</button>
</form>
);
}Write a handler inline and you don't type the event at all: TypeScript knows the type of onChange on an <input> and gives it to the parameter.
function TaskTitle() {
const [title, setTitle] = useState("");
// e is React.ChangeEvent<HTMLInputElement>
return <input value={title} onChange={(e) => setTitle(e.target.value)} />;
}Move the handler into a named function and that context is gone. Under strict an untyped parameter is an implicit any error, so you annotate it. react.dev's tip: hover over the prop (onChange) in the editor to see which event type it expects.
function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
console.log(event.target.value);
}
// or type the whole function with a handler type
const handleKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (event) => {
if (event.key === "Escape") event.currentTarget.blur();
};The everyday ones are ChangeEvent (inputs, selects, textareas), MouseEvent, KeyboardEvent and FocusEvent. For onSubmit the current types use SubmitEvent<HTMLFormElement>; the older FormEvent still compiles but is marked deprecated. The type parameter is the element the handler is attached to. These are React's types: import them from react or write React.MouseEvent. A bare MouseEvent is the DOM's own type, and a handler typed with it does not fit onClick.
target or currentTarget
currentTarget is the element the handler is attached to, and it is typed as that element. target is where the event started, possibly a child, so for a click it is typed only as EventTarget:
function handleClick(event: React.MouseEvent<HTMLButtonElement>) {
// Error: 'disabled' does not exist on type 'EventTarget'
event.target.disabled = true;
event.currentTarget.disabled = true;
}Change events are the exception: their target is typed as the form element, so e.target.value works in onChange. Elsewhere use currentTarget instead of a cast like event.target as HTMLButtonElement.
Callback props
A component's own event props should pass values, not DOM events. The parent of an AddTaskForm wants a title:
type AddTaskFormProps = {
onAdd: (title: string) => void;
};
function AddTaskForm({ onAdd }: AddTaskFormProps) {
const [title, setTitle] = useState("");
function handleSubmit(event: React.SubmitEvent<HTMLFormElement>) {
event.preventDefault();
onAdd(title.trim());
setTitle("");
}
return (
<form onSubmit={handleSubmit}>
<input value={title} onChange={(e) => setTitle(e.target.value)} />
<button type="submit">Add</button>
</form>
);
}useState: inference, unions and null
useState tipini ilkin dəyərdən götürür: useState(0) number, useState("") string, useState(false) isə boolean saxlayır. İlkin dəyər state-in nə saxlaya biləcəyini artıq göstərirsə, bu kifayətdir. Göstərmədiyi üç tipik hal:
const [user, setUser] = useState(null);
// Xəta: 'User' tipi 'SetStateAction<null>'-a mənimsədilə bilməz
setUser(currentUser);
const [tags, setTags] = useState([]);
// Xəta: 'string' tipi 'never'-ə mənimsədilə bilməz
setTags(["sale"]);
const [status, setStatus] = useState("idle");
// Xəta yoxdur: status istənilən sətirdir, hərf səhvi də daxil
setStatus("svaed");Tipi tip arqumenti kimi ötür:
const [user, setUser] = useState<User | null>(null);
const [tags, setTags] = useState<string[]>([]);
const [status, setStatus] = useState<"idle" | "saving" | "saved">("idle");User | null olanda TypeScript istifadədən əvvəl yoxlamağa məcbur edir: user?.name və ya erkən if (!user) return <SignInLink />. Bu, deməkdir. İlkin dəyəri olmayan tip arqumenti, useState<User>(), User | undefined verir.
Yoxlamadan yayınmaq üçün yalan danışma: useState<User>({} as User) kompilyasiya olunur, amma data gələnə qədər user.name undefined-dir və tip artıq səni xəbərdar etmir.
Bayraqları yox, vəziyyətləri modelləşdir
Ayrı-ayrı boolean-lar komponentin mənasız vəziyyətlərə düşməsinə imkan verir: error təyin olunduğu halda isLoading, və ya xəta ilə yanaşı data. eyni anda yalnız bir vəziyyət saxlayır və TypeScript-ə hər vəziyyətdə hansı sahələrin olduğunu bildirir:
type ProfileState =
| { status: "loading" }
| { status: "error"; message: string }
| { status: "ready"; user: User };
function Profile() {
const [state, setState] = useState<ProfileState>({ status: "loading" });
if (state.status === "loading") return <p>Loading...</p>;
if (state.status === "error") return <p role="alert">{state.message}</p>;
return <h1>{state.user.name}</h1>;
}Hər yoxlamadan sonra TypeScript state-i daraldır: state.message yalnız xəta budağında, state.user isə yalnız sonuncu budaqda mövcuddur. Yeniləmələr də yoxlanır: user olmadan setState({ status: "ready" }) kompilyasiya olunmur, ona görə komponent göstərəcək heç nə olmadan "ready" vəziyyətinə keçə bilmir.
useState takes its type from the initial value: useState(0) holds a number, useState("") a string, useState(false) a boolean. That is enough when the initial value already shows what the state can hold. Three common cases where it does not:
const [user, setUser] = useState(null);
// Error: 'User' is not assignable to 'SetStateAction<null>'
setUser(currentUser);
const [tags, setTags] = useState([]);
// Error: 'string' is not assignable to 'never'
setTags(["sale"]);
const [status, setStatus] = useState("idle");
// No error: status is any string, typo included
setStatus("svaed");Pass the type as a type argument:
const [user, setUser] = useState<User | null>(null);
const [tags, setTags] = useState<string[]>([]);
const [status, setStatus] = useState<"idle" | "saving" | "saved">("idle");With User | null, TypeScript makes you check before use: user?.name, or an early if (!user) return <SignInLink />. That is at work. A type argument without an initial value, useState<User>(), gives User | undefined.
Don't lie to skip the check: useState<User>({} as User) compiles, but user.name is undefined until the data arrives, and the type no longer warns you.
Model states, not flags
Separate booleans let a component be in states that make no sense: isLoading while error is set, or data together with an error. A keeps exactly one state at a time and tells TypeScript which fields exist in each:
type ProfileState =
| { status: "loading" }
| { status: "error"; message: string }
| { status: "ready"; user: User };
function Profile() {
const [state, setState] = useState<ProfileState>({ status: "loading" });
if (state.status === "loading") return <p>Loading...</p>;
if (state.status === "error") return <p role="alert">{state.message}</p>;
return <h1>{state.user.name}</h1>;
}After each check TypeScript narrows state: state.message exists only in the error branch, state.user only in the last one. Updates are checked too: setState({ status: "ready" }) without a user does not compile, so the component can't reach "ready" with nothing to show.
useRef: DOM nodes and mutable values
useRef-in iki işi var və tip məhz hansı iş üçün istifadə olunduğundan asılıdır.
DOM node-u. null ilə başla və elementin tipini yaz. React commit-dən sonra current-ə node-u yazır, element silinəndə isə onu yenidən null edir, ona görə tip HTMLInputElement | null-dur və TypeScript səni onu yoxlamağa məcbur edir:
function TaskFilter() {
const inputRef = useRef<HTMLInputElement>(null);
function focusInput() {
// Xəta: 'inputRef.current' 'null' ola bilər
inputRef.current.focus();
inputRef.current?.focus();
}
return (
<>
<input ref={inputRef} />
<button onClick={focusInput}>Filter</button>
</>
);
}Elementin tipi ref-in bağlandığı yerə uyğun olmalıdır: <input ref={...}>-ə ötürülən useRef<HTMLDivElement>(null) tip xətasıdır.
Dəyişkən dəyər: render-lər arasında qalan, amma yeni render-ə səbəb olmayan dəyər, məsələn, taymerin id-si. Onun tipi ilkin dəyərdən və ya tip arqumentindən gəlir:
function CopyButton({ text }: { text: string }) {
const [copied, setCopied] = useState(false);
const hideTimer = useRef<number | null>(null);
async function copy() {
await navigator.clipboard.writeText(text);
setCopied(true);
if (hideTimer.current !== null) window.clearTimeout(hideTimer.current);
hideTimer.current = window.setTimeout(() => setCopied(false), 2000);
}
return <button onClick={copy}>{copied ? "Copied" : "Copy"}</button>;
}window.setTimeout number qaytarır. @types/node yüklənibsə, sadəcə setTimeout isə Node-un Timeout obyektini qaytarır, ona görə ortaq kodda çox vaxt ReturnType<typeof setTimeout> yazılır. current-i dəyişmək heç vaxt render-ə səbəb olmur: dəyər ekranda görünməlidirsə, onun yeri state-dir.
React 19-un tiplərində nə dəyişdi
useRefarqument tələb edir.useRef<HTMLDivElement>()xətadır ("Expected 1 argument");useRef<HTMLDivElement>(null)yaz, boş başlayan dəyər üçün isəuseRef<number>(undefined).- Yalnız bir
RefObject<T>var vəcurrenthəmişə yazıla biləndir. Köhnə tiplərdəuseRef<number>(null)yalnız oxunan ref verirdi;MutableRefObjectindi deprecated-dir. - Ref callback-i cleanup funksiyası qaytara bilər, başqa heç nə.
ref={(node) => (instance = node)}node-u qaytarır, ona görə artıq kompilyasiya olunmur; arrow funksiyaya blok gövdə ver:ref={(node) => { instance = node; }}.
useRef has two jobs, and the type follows from the job.
A DOM node. Start with null and name the element type. React sets current to the node after the commit and back to null when the element is removed, so the type is HTMLInputElement | null and TypeScript makes you check it:
function TaskFilter() {
const inputRef = useRef<HTMLInputElement>(null);
function focusInput() {
// Error: 'inputRef.current' is possibly 'null'
inputRef.current.focus();
inputRef.current?.focus();
}
return (
<>
<input ref={inputRef} />
<button onClick={focusInput}>Filter</button>
</>
);
}The element type must match where the ref goes: a useRef<HTMLDivElement>(null) passed to <input ref={...}> is a type error.
A mutable value that survives re-renders without causing one, such as a timer id. Its type comes from the initial value or from a type argument:
function CopyButton({ text }: { text: string }) {
const [copied, setCopied] = useState(false);
const hideTimer = useRef<number | null>(null);
async function copy() {
await navigator.clipboard.writeText(text);
setCopied(true);
if (hideTimer.current !== null) window.clearTimeout(hideTimer.current);
hideTimer.current = window.setTimeout(() => setCopied(false), 2000);
}
return <button onClick={copy}>{copied ? "Copied" : "Copy"}</button>;
}window.setTimeout returns a number. With @types/node loaded, a bare setTimeout returns Node's Timeout object instead, which is why shared code often writes ReturnType<typeof setTimeout>. Changing current never re-renders: if the screen must show the value, it belongs in state.
What React 19's types changed
useRefrequires an argument.useRef<HTMLDivElement>()is an error ("Expected 1 argument"); writeuseRef<HTMLDivElement>(null), oruseRef<number>(undefined)for a value that starts empty.- There is one
RefObject<T>, andcurrentis always writable. In older typesuseRef<number>(null)gave a read-only ref;MutableRefObjectis now deprecated. - A ref callback may return a cleanup function, and nothing else.
ref={(node) => (instance = node)}returns the node, so it no longer compiles; give the arrow a block body:ref={(node) => { instance = node; }}.
useReducer with action unions, and typed context
State-in bir neçə hissəsi birlikdə dəyişəndə useReducer keçidləri bir funksiyaya toplayır. Action-ları kimi tiplə: hər action-ın literal type-ı və yalnız ona lazım olan sahələri olur.
type Line = { id: string; qty: number };
type CartAction =
| { type: "added"; id: string }
| { type: "removed"; id: string }
| { type: "cleared" };
function cartReducer(lines: Line[], action: CartAction): Line[] {
switch (action.type) {
case "added":
return lines.some((l) => l.id === action.id)
? lines.map((l) => (l.id === action.id ? { ...l, qty: l.qty + 1 } : l))
: [...lines, { id: action.id, qty: 1 }];
case "removed":
return lines.filter((l) => l.id !== action.id);
case "cleared":
return [];
default: {
const unhandled: never = action;
throw new Error(`Unknown action: ${JSON.stringify(unhandled)}`);
}
}
}
function Cart() {
const [lines, dispatch] = useReducer(cartReducer, []);
return <button onClick={() => dispatch({ type: "cleared" })}>Clear ({lines.length})</button>;
}Hər case-in içində TypeScript action-ı daraldır: action.id "added" və "removed"-də var, "cleared"-də yoxdur. dispatch da yoxlanır: id-siz dispatch({ type: "removed" }) xətadır, səhv yazılmış type da. never-ə mənimsətmə tamlıq (exhaustiveness) yoxlamasıdır: dördüncü action əlavə edib onun case-ini unutsan, bu sətir kompilyasiya olunmaz. throw yenə də lazımdır: JSON.parse ilə bərpa olunan action datada nə yazılıbsa, odur.
React 19-un tipləri state və action tiplərini reducer-dən çıxarır, react.dev-in upgrade guide-ı isə useReducer-ə tip arqumenti ötürməməyi tövsiyə edir: bunun əvəzinə reducer-in parametrlərinə annotasiya yaz. Mütləq lazımdırsa, forma indi useReducer<State, [Action]>-dir; köhnə useReducer<React.Reducer<State, Action>> artıq kompilyasiya olunmur.
Tiplənmiş context
createContext tipini default dəyərdən götürür. Mənalı default olmayanda, məsələn, daxil olmuş istifadəçinin sessiyası üçün, tipə null əlavə et və useContext-i xəta atan hook-a bük ki, istifadəçilər heç vaxt null olmayan dəyər alsın:
type Session = { user: User; signOut: () => void };
const SessionContext = createContext<Session | null>(null);
export function useSession(): Session {
const session = useContext(SessionContext);
if (session === null) throw new Error("useSession must be used inside <SessionProvider>");
return session;
}
export function SessionProvider({ session, children }: { session: Session; children: ReactNode }) {
return <SessionContext value={session}>{children}</SessionContext>;
}React 19-da context-in özü provider kimi render olunur. Provider-dən kənardakı komponent isə dərhal aydın mesajla dayanır.
When several pieces of state change together, useReducer moves the transitions into one function. Type the actions as a : every action has a literal type and only the fields it needs.
type Line = { id: string; qty: number };
type CartAction =
| { type: "added"; id: string }
| { type: "removed"; id: string }
| { type: "cleared" };
function cartReducer(lines: Line[], action: CartAction): Line[] {
switch (action.type) {
case "added":
return lines.some((l) => l.id === action.id)
? lines.map((l) => (l.id === action.id ? { ...l, qty: l.qty + 1 } : l))
: [...lines, { id: action.id, qty: 1 }];
case "removed":
return lines.filter((l) => l.id !== action.id);
case "cleared":
return [];
default: {
const unhandled: never = action;
throw new Error(`Unknown action: ${JSON.stringify(unhandled)}`);
}
}
}
function Cart() {
const [lines, dispatch] = useReducer(cartReducer, []);
return <button onClick={() => dispatch({ type: "cleared" })}>Clear ({lines.length})</button>;
}Inside each case TypeScript narrows action: action.id exists in "added" and "removed", not in "cleared". dispatch is checked as well: dispatch({ type: "removed" }) without an id is an error, and so is a misspelled type. The never assignment is the exhaustiveness check: add a fourth action and forget its case, and that line stops compiling. The throw still matters: an action rebuilt from JSON.parse is whatever the data says.
React 19's types infer state and action types from the reducer, and react.dev's upgrade guide recommends not passing type arguments to useReducer: annotate the reducer's parameters instead. If you must, the form is now useReducer<State, [Action]>; the old useReducer<React.Reducer<State, Action>> no longer compiles.
Typed context
createContext takes its type from the default value. When there is no sensible default, such as the signed-in session, put null in the type and wrap useContext in a hook that throws, so consumers get a value that is never null:
type Session = { user: User; signOut: () => void };
const SessionContext = createContext<Session | null>(null);
export function useSession(): Session {
const session = useContext(SessionContext);
if (session === null) throw new Error("useSession must be used inside <SessionProvider>");
return session;
}
export function SessionProvider({ session, children }: { session: Session; children: ReactNode }) {
return <SessionContext value={session}>{children}</SessionContext>;
}In React 19 the context itself renders as the provider. A component outside the provider fails at once with a clear message.
Wrapping native elements: ComponentProps and ref as a prop
Dizayn sisteminin Button-u <button>-un qəbul etdiyi hər şeyi (type, disabled, aria-*, onClick...) əl ilə sadalamadan qəbul etməlidir. ComponentProps<"button"> məhz bu siyahıdır, React-in JSX tiplərindən götürülür.
import type { ComponentProps } from "react";
type ButtonProps = ComponentProps<"button"> & {
variant?: "primary" | "ghost";
};
export function Button({ variant = "primary", className, ...rest }: ButtonProps) {
return <button {...rest} className={`btn btn-${variant} ${className ?? ""}`} />;
}İstifadə etdiyin props-u destructuring ilə götür, qalanını elementə spread et; children, handler-lər və atributlar ötürülür və istifadə yerində yoxlanır (<Button type="sumbit"> xətadır). İcra zamanı sıra vacibdir: {...rest}-dən sonrakı atributlar çağıranın dəyərlərini əvəz edir, ondan əvvəlkilər isə çağıranın əvəz edə biləcəyi default-lardır, hətta açıq undefined ilə də.
React 19-da ref prop-dur
Funksiya komponenti indi ref-i digər prop-lar kimi alır və ComponentProps<"button"> onu da əhatə edir, ona görə yuxarıdakı spread çağıranın ref-ini artıq <button>-a ötürür. react.dev: forwardRef artıq lazım deyil və gələcək buraxılışda deprecated olacaq. Ref daxili elementə aiddirsə, onu özün elan et:
type TextFieldProps = Omit<ComponentProps<"input">, "ref"> & {
label: string;
ref?: Ref<HTMLInputElement>;
};
function TextField({ label, id, ref, ...rest }: TextFieldProps) {
const generatedId = React.useId();
const inputId = id ?? generatedId;
return (
<div className="field">
<label htmlFor={inputId}>{label}</label>
<input id={inputId} ref={ref} {...rest} />
</div>
);
}Hansı köməkçi tip nə vaxt:
ComponentProps<"input">(elementlər üçünComponentPropsWithRefilə eynidir)ref-i də əhatə edir. Qalan props, ref də daxil, həmin elementə düşəndə bundan istifadə et.ComponentPropsWithoutRef<"input">-darefyoxdur. Komponent ref-i həmin elementə qoymayanda bundan istifadə et ki, çağıran heç yerə getməyən ref ötürə bilməsin.ComponentProps<typeof DatePicker>mövcud komponentin props-unu verir; kitabxana props tipini export etməyəndə əlverişlidir.
Native prop-u dəyişmək: əvvəlcə Omit
Native prop-a başqa tip vermək üçün öz tipini əlavə etməzdən əvvəl onu çıxar. Sadə intersection hər ikisini saxlayır və onChange eyni anda həm React change handler-i, həm də (value: string) => void olmalı olardı:
type SelectProps = Omit<ComponentProps<"select">, "value" | "onChange"> & {
value: string;
onChange: (value: string) => void;
};TypeScript adı düzgün identifikator olmayan JSX atributlarını yoxlamır, ona görə data-testid elan olunmadan istənilən komponentdən keçir.
A design-system Button should accept everything a <button> accepts (type, disabled, aria-*, onClick...) without listing it by hand. ComponentProps<"button"> is that list, taken from React's JSX types.
import type { ComponentProps } from "react";
type ButtonProps = ComponentProps<"button"> & {
variant?: "primary" | "ghost";
};
export function Button({ variant = "primary", className, ...rest }: ButtonProps) {
return <button {...rest} className={`btn btn-${variant} ${className ?? ""}`} />;
}Destructure the props you use and spread the rest onto the element; children, handlers and attributes pass through, checked at the call site (<Button type="sumbit"> is an error). Order matters at run time: attributes after {...rest} override the caller's, attributes before it are defaults the caller can replace, even with an explicit undefined.
ref is a prop in React 19
A function component now receives ref like any other prop, and ComponentProps<"button"> includes it, so the spread above already passes a caller's ref to the <button>. react.dev: forwardRef is no longer necessary and will be deprecated in a future release. When the ref belongs to an inner element, declare it yourself:
type TextFieldProps = Omit<ComponentProps<"input">, "ref"> & {
label: string;
ref?: Ref<HTMLInputElement>;
};
function TextField({ label, id, ref, ...rest }: TextFieldProps) {
const generatedId = React.useId();
const inputId = id ?? generatedId;
return (
<div className="field">
<label htmlFor={inputId}>{label}</label>
<input id={inputId} ref={ref} {...rest} />
</div>
);
}Which helper to use:
ComponentProps<"input">(for elements, the same asComponentPropsWithRef) includesref. Use it when the rest props, ref included, land on that element.ComponentPropsWithoutRef<"input">has noref. Use it when the component does not put the ref on that element, so a caller cannot pass a ref that silently goes nowhere.ComponentProps<typeof DatePicker>gives the props of an existing component, handy when a library does not export its props type.
Changing a native prop: Omit first
To give a native prop another type, remove it before adding yours. A plain intersection keeps both, and onChange would have to be a React change handler and (value: string) => void at once:
type SelectProps = Omit<ComponentProps<"select">, "value" | "onChange"> & {
value: string;
onChange: (value: string) => void;
};TypeScript does not check JSX attributes whose name is not a valid identifier, so data-testid passes through any component undeclared.
Escape hatches that hide bugs
React kodundakı tip xətalarının çoxunun düzgün həlli və tez bir qaçış yolu olur. Qaçış yolu kompilyasiya olunur, bug isə icra vaxtına keçir.
Yalan danışan placeholder state.
function Greeting() {
const [user, setUser] = useState<User>({} as User);
// Kompilyasiya olunur, sonra xəta atır: data gələnə qədər user.name undefined-dir
return <p>Hello, {user.name.toUpperCase()}</p>;
}{} as User (və ya null!) TypeScript-ə istifadəçinin artıq mövcud olduğunu deyir. State-i User | null kimi tiplə və olmayan halı da render et.
Ref-də !. inputRef.current!.focus() node-un mövcud olduğunu iddia edir. Bu, komponent mount olunduqdan sonra həmişə render olunan element üçün doğrudur, şərtin arxasındakı element üçün isə yox. inputRef.current?.focus() cəmi bir simvol artıqdır.
Event target-i cast etmək. Klik handler-indəki (event.target as HTMLInputElement).value klik düymənin içindəki ikonadan başlayanda da kompilyasiya olunur. event.currentTarget isə handler-in bağlandığı elementin tipini daşıyır.
Event və props üçün any. (e: any) => ... bütün handler üçün yoxlamanı söndürür, props: any isə bütün komponent üçün. Bunun əvəzinə kursoru prop-un üzərinə gətir və event tipinə bax.
Qlobal JSX namespace-i. React 19-un tipləri artıq qlobal JSX elan etmir, ona görə JSX.Element qaytarma tipi "Cannot find namespace 'JSX'" xətası verir. React.JSX.Element yaz və ya qaytarma tipini TypeScript-in özünə burax. JSX.IntrinsicElements-dəki custom element elanları react və ya JSX runtime modulu üçün declare module blokuna köçür.
Ref callback-lərində implicit return. ref={(node) => (instance = node)} node-u qaytarır, React 19-un tipləri isə qaytarılan dəyər kimi yalnız cleanup funksiyasına icazə verir. Blok gövdədən istifadə et.
Elementin props-unu oxumaq. ReactElement["props"] indi any yox, unknown-dur, ona görə children.props.title oxuyan kod kompilyasiya olunmur. Bunun əvəzinə datanı props kimi ötür, elementləri həqiqətən yoxladığın yerdə isə elementə tip arqumenti ver (ReactElement<{ title: string }>).
JSX-in üstündə @ts-ignore. O, növbəti sətirdəki bütün xətaları susdurur, hələ heç kimin görmədiyi xətaları da. Qaçış yolu labüddürsə, səbəbi yazılmış @ts-expect-error heç olmasa xəta aradan qalxanda özü xəta verir.
Most type errors in React code have a correct fix and a quick escape. The escape compiles, and the bug moves to run time.
A placeholder state that lies.
function Greeting() {
const [user, setUser] = useState<User>({} as User);
// Compiles, then throws: user.name is undefined until the data arrives
return <p>Hello, {user.name.toUpperCase()}</p>;
}{} as User (or null!) tells TypeScript the user is already there. Type the state as User | null and render the missing case.
! on a ref. inputRef.current!.focus() claims the node exists. That holds for an element that is always rendered once the component has mounted, not for one behind a condition. inputRef.current?.focus() costs one character.
Casting the event target. (event.target as HTMLInputElement).value in a click handler compiles even when the click started on an icon inside the button. event.currentTarget is typed as the element the handler is attached to.
any for events and props. (e: any) => ... turns off checking for the whole handler, props: any for the whole component. Hover the prop to find the event type instead.
The global JSX namespace. React 19's types no longer declare a global JSX, so a return type JSX.Element fails with "Cannot find namespace 'JSX'". Write React.JSX.Element, or let TypeScript infer the return type. Declarations for custom elements in JSX.IntrinsicElements move into a declare module block for react or the JSX runtime module.
Implicit returns from ref callbacks. ref={(node) => (instance = node)} returns the node, and React 19's types allow only a cleanup function as the return value. Use a block body.
Reading props of an element. ReactElement["props"] is now unknown instead of any, so code that reads children.props.title stops compiling. Pass the data as props instead, or give the element a type argument (ReactElement<{ title: string }>) where you really inspect elements.
@ts-ignore above JSX. It silences every error on the next line, including ones nobody has seen yet. If an escape is unavoidable, @ts-expect-error with a reason at least fails once the error is gone.
Generic components
Siyahı, cədvəl və ya seçici istənilən element tipi ilə işləyir, amma hər istifadədə elementlərlə callback-lər arasındakı əlaqə qorunmalıdır: elementlər məhsuldursa, renderItem məhsul almalıdır. Funksiya komponenti funksiyadır, ona görə komponent də generic funksiya kimi işləyir.
import type { Key, ReactNode } from "react";
type ListProps<T> = {
items: readonly T[];
getKey: (item: T) => Key;
renderItem: (item: T) => ReactNode;
emptyText?: string;
};
export function List<T>({ items, getKey, renderItem, emptyText = "Nothing here" }: ListProps<T>) {
if (items.length === 0) return <p>{emptyText}</p>;
return (
<ul>
{items.map((item) => (
<li key={getKey(item)}>{renderItem(item)}</li>
))}
</ul>
);
}
<List items={products} getKey={(p) => p.sku} renderItem={(p) => `${p.title}: ${p.price}`} />;
// Xəta: məhsul tipində 'name' xassəsi yoxdur
<List items={products} getKey={(p) => p.sku} renderItem={(p) => p.name} />;T istifadə yerində items-dən çıxarılır və callback-lər ona qarşı yoxlanır. Çıxarmağa heç nə olmayanda, məsələn, boş massiv literalında, tip arqumentini JSX-də ötür: <List<Product> items={[]} ... />. readonly T[] as const massivləri də qəbul edir. Məhdudiyyətlər (constraint) funksiyalardakı kimi işləyir: function Table<T extends { id: string }> row.id-ni key kimi işlədə bilər və id-si olmayan sətirləri qəbul etmir.
.tsx fayllarında arrow funksiyalar
.tsx faylında arrow funksiyanın qarşısındakı <T> JSX teqi kimi oxunur. <T,> yaz və ya funksiya elanından istifadə et:
export const Grid = <T,>({ items }: { items: T[] }) => <div>{items.length}</div>;Generic komponentlər və ref-lər
forwardRef tip parametrini saxlamır: generic komponenti ona bükəndə istifadə yerində T unknown olur, köhnə kodda onun ətrafında cast-ların yazılmasının səbəbi də budur. React 19-da ref prop olduğu üçün komponent ref?: Ref<HTMLUListElement>-i digər prop-lar kimi elan edir və generic qalır.
Nə vaxt lazım deyil
Tip parametri ən azı iki yeri bir-birinə bağlamalıdır. T yalnız items: T[]-də görünürsə və heç nə elementi çağırana geri vermirsə, items: unknown[] və ya konkret tip eyni şeyi daha az səs-küylə deyir. Generic komponentlər həm də daha uzun xəta mesajları yaradır, ona görə onları həqiqətən ortaq istifadə olunan baza komponentləri üçün saxla.
A list, a table or a picker works for any item type, but each use should keep the link between the items and the callbacks: if the items are products, renderItem receives a product. A function component is a function, so a component works exactly like a generic function.
import type { Key, ReactNode } from "react";
type ListProps<T> = {
items: readonly T[];
getKey: (item: T) => Key;
renderItem: (item: T) => ReactNode;
emptyText?: string;
};
export function List<T>({ items, getKey, renderItem, emptyText = "Nothing here" }: ListProps<T>) {
if (items.length === 0) return <p>{emptyText}</p>;
return (
<ul>
{items.map((item) => (
<li key={getKey(item)}>{renderItem(item)}</li>
))}
</ul>
);
}
<List items={products} getKey={(p) => p.sku} renderItem={(p) => `${p.title}: ${p.price}`} />;
// Error: property 'name' does not exist on the product type
<List items={products} getKey={(p) => p.sku} renderItem={(p) => p.name} />;T is inferred from items at the call site, and the callbacks are checked against it. When there is nothing to infer from, such as an empty array literal, pass the type argument in JSX: <List<Product> items={[]} ... />. readonly T[] also accepts as const arrays. Constraints work as in functions: function Table<T extends { id: string }> may use row.id as the key and rejects rows without an id.
Arrow functions in .tsx files
In a .tsx file, <T> in front of an arrow function parses as a JSX tag. Write <T,>, or use a function declaration:
export const Grid = <T,>({ items }: { items: T[] }) => <div>{items.length}</div>;Generic components and refs
forwardRef does not keep a type parameter: wrap a generic component in it and T becomes unknown at the call site, which is why older code needed casts around it. With ref as a prop in React 19, the component declares ref?: Ref<HTMLUListElement> like any other prop and stays generic.
When not to
A type parameter has to connect at least two places. If T appears only in items: T[] and nothing hands an item back to the caller, items: unknown[] or a concrete type says the same with less noise. Generic components also produce longer error messages, so keep them for real shared building blocks.
Props that depend on each other
Bəzi props yalnız birlikdə mənalıdır: düymə ya link (href), ya da əməliyyatdır (onClick); modal ya idarə olunandır (open və onClose), ya da yox (defaultOpen). Hər şey üçün optional props istənilən qarışığa, o cümlədən "hər ikisi" və "heç biri" variantlarına icazə verir. isə yalnız düzgün birləşmələri sadalayır:
type ActionProps =
| { as: "link"; href: string; children: ReactNode }
| { as: "button"; onClick: () => void; children: ReactNode };
function Action(props: ActionProps) {
if (props.as === "link") return <a href={props.href}>{props.children}</a>;
return (
<button type="button" onClick={props.onClick}>
{props.children}
</button>
);
}
<Action as="link" href="/pricing">Pricing</Action>;
// Xəta: button variantında 'href' yoxdur
<Action as="button" href="/pricing" onClick={track}>Pricing</Action>;Narrowing props.as üzərində işləyir. Parametr siyahısında destructuring-dən sonra da işləyir, bir şərtlə ki, destructuring edilən hər xassə bütün üzvlərdə olsun və dəyişənlərə yenidən dəyər mənimsədilməsin (TypeScript 4.6 və sonrakı versiyalar): { kind: "text"; value: string } | { kind: "number"; value: number } olanda kind yoxlaması value-nu daraldır. ...rest obyekti isə daralmır, ona görə qalanını spread edən komponent destructuring-dən əvvəl props.as-ı yoxlayır.
Discriminant-sız union-lar müstəsna deyil
TypeScript union-ın bir üzvünə uyğun gələn props-u, onlarda başqa üzvün props-u olsa belə, qəbul edir:
type ModalProps =
| { open: boolean; onClose: () => void }
| { defaultOpen: boolean };
declare function Modal(props: ModalProps): ReactNode;
// Kompilyasiya olunur: birinci üzv uyğun gəlir, defaultOpen isə yanında gəlir
<Modal open onClose={closeModal} defaultOpen />;Qarışığı digər üzvün açarları üçün ?: never ilə qadağan et:
type ModalProps =
| { open: boolean; onClose: () => void; defaultOpen?: never }
| { defaultOpen: boolean; open?: never; onClose?: never };İndi eyni JSX xəta verir. Bu üsul bayraqdan asılı dəyəri də tipləyir: { multiple?: false; value: string } | { multiple: true; value: string[] }.
Qiyməti
Omit<ActionProps, "children"> hər üzv üçün ayrıca işləmir: union üzərində Omit yalnız bütün üzvlərdə ortaq olan açarları saxlayır, ona görə href və onClick yox olur. Belə komponenti bükmək üçün distributiv versiya lazımdır: T extends unknown ? Omit<T, K> : never (union üzərində paylanan ). Xəta mesajları da böyüyür. Union-lardan yanlış birləşmənin real bug olacağı yerdə istifadə et, hər cüt prop üçün yox.
Some props only make sense together: a button is either a link (href) or an action (onClick); a modal is either controlled (open and onClose) or not (defaultOpen). Optional props for everything allow every mix, including both and neither. A lists the valid combinations instead:
type ActionProps =
| { as: "link"; href: string; children: ReactNode }
| { as: "button"; onClick: () => void; children: ReactNode };
function Action(props: ActionProps) {
if (props.as === "link") return <a href={props.href}>{props.children}</a>;
return (
<button type="button" onClick={props.onClick}>
{props.children}
</button>
);
}
<Action as="link" href="/pricing">Pricing</Action>;
// Error: 'href' does not exist on the button variant
<Action as="button" href="/pricing" onClick={track}>Pricing</Action>;Narrowing works on props.as. It also works after destructuring in the parameter list, as long as every destructured property exists in all members and the variables are never reassigned (TypeScript 4.6 and later): with { kind: "text"; value: string } | { kind: "number"; value: number }, a check on kind narrows value. A ...rest object is not narrowed, so a component that spreads the rest checks props.as before destructuring.
Unions without a discriminant are not exclusive
TypeScript accepts props that match one member of a union even when they carry props of another member:
type ModalProps =
| { open: boolean; onClose: () => void }
| { defaultOpen: boolean };
declare function Modal(props: ModalProps): ReactNode;
// Compiles: the first member matches, and defaultOpen comes along
<Modal open onClose={closeModal} defaultOpen />;Forbid the mix with ?: never for the other member's keys:
type ModalProps =
| { open: boolean; onClose: () => void; defaultOpen?: never }
| { defaultOpen: boolean; open?: never; onClose?: never };Now the same JSX is an error. The pattern also types a value that depends on a flag: { multiple?: false; value: string } | { multiple: true; value: string[] }.
The cost
Omit<ActionProps, "children"> does not work per member: Omit over a union keeps only the keys common to all members, so href and onClick disappear. Wrapping such a component needs a distributive version, T extends unknown ? Omit<T, K> : never (a that distributes over the union). Error messages grow too. Use unions where an invalid combination would be a real bug, not for every pair of props.
Interview tips
30 saniyəlik cavab. "Props-u obyekt tipi kimi tipləyirəm, qalanını isə TypeScript-in özü çıxarır: inline handler-lər event tipini prop-dan, useState ilkin dəyərdən, useReducer isə reducer-dən alır. TypeScript-in özünün bilə bilmədiyi yerlərdə tip əlavə edirəm: useState<User | null>(null), useRef<HTMLInputElement>(null), JSX-dən çıxarılmış handler-lər. Native elementlərin wrapper-ləri ComponentProps<"button"> qəbul edir və React 19-da ref-i prop kimi alır. Yalnız müəyyən birləşmələrdə mənalı olan props üçün discriminated union, təkrar istifadə olunan siyahılar üçün isə generic komponent yazıram."
Gözlənilən suallar
- Children üçün
ReactNode,ReactElement, yoxsaJSX.Element? Render oluna bilən hər şey üçünReactNode, yalnız JSX elementləri üçünReactElement;JSX.ElementJSX ifadəsinin tipidir (React 19-un tiplərindəReact.JSX.Element). - JSX-dən çıxarılmış
onChangehandler-ini necə tipləyirsən? Parametr üçünReact.ChangeEvent<HTMLInputElement>, funksiya üçün isəReact.ChangeEventHandler<HTMLInputElement>.targetiləcurrentTargetfərqini də əlavə et. - React 19-un tiplərində nə dəyişdi?
useRefarqument tələb edir və bütün ref-lər dəyişkəndir; ref callback-ləri yalnız cleanup qaytarır; qlobalJSXyoxdur;ReactElement-in props-u default haldaunknown-dur;useReducertipləri reducer-dən çıxarır;refprop-dur, ona görəforwardRefartıq lazım deyil. - Bütün native props-u qəbul edən
Button-u necə tipləyərdin?ComponentProps<"button">üstəgəl öz props-un, dəyişdiyin props üçünOmit, qalanı isə elementə spread olunur. - İki prop-u bir-birini istisna edən necə edirsən? Discriminated union ilə, discriminant yoxdursa,
?: neverilə. - Generic
Select<T>-ni necə tipləyirsən? Generic funksiya komponenti kimi;.tsx-dəki arrow funksiyalarda<T,>-ni vəforwardRef-inT-ni itirdiyini qeyd et.
Bal itirdən səhvlər
- Xətaları
as,!və yaanyilə susdurmaq, xüsusənuseState({} as User). React.FC-nin məcburi olduğunu və yachildrenəlavə etdiyini demək (React 18 tiplərindən bəri əlavə etmir).- Tipləri icra zamanı yoxlaması saymaq: API cavabından doldurulan prop cavabın özü qədər düzgündür. Tiplər datanı təsvir edir, onu yoxlamır.
Senior səviyyəni göstərən məqamlar
Sintaksisdən çox kompromislərdən danış: annotasiyalar əvəzinə tipin çıxarılması, yalnız yanlış birləşmənin real bug olduğu yerdə union-lar, yalnız ortaq baza komponentləri üçün generic komponentlər və dizayn sistemində native props-u, ref-ləri və əlçatanlıq atributlarını ötürən wrapper tipləri. Tip yoxlamasının harada dayandığını bildiyini göstər: datanın tətbiqə daxil olduğu sərhəddə.
A 30-second answer. "I type the props as an object type and let TypeScript infer the rest: inline handlers get their event type from the prop, useState from its initial value, useReducer from the reducer. I add types where inference can't know: useState<User | null>(null), useRef<HTMLInputElement>(null), handlers moved out of JSX. Wrappers around native elements take ComponentProps<"button">, and in React 19 they receive ref as a prop. Props that only make sense in certain combinations get a discriminated union, and reusable lists become generic components."
Questions you are likely to get
ReactNode,ReactElementorJSX.Elementfor children?ReactNodefor anything renderable,ReactElementfor JSX elements only;JSX.Elementis the type of a JSX expression (React.JSX.Elementin React 19's types).- How do you type an
onChangehandler moved out of JSX?React.ChangeEvent<HTMLInputElement>for the parameter, orReact.ChangeEventHandler<HTMLInputElement>for the function. AddtargetvscurrentTarget. - What changed in React 19's types?
useRefneeds an argument and every ref is mutable; ref callbacks return only a cleanup; no globalJSX;ReactElementprops default tounknown;useReducerinfers from the reducer;refis a prop, soforwardRefis no longer needed. - How would you type a
Buttonthat takes every native prop?ComponentProps<"button">plus your own props,Omitfor the ones you change, the rest spread onto the element. - How do you make two props mutually exclusive? A discriminated union, or
?: neverwhen there is no discriminant. - How do you type a generic
Select<T>? As a generic function component; mention<T,>in.tsxarrow functions and thatforwardReflosesT.
Mistakes that cost points
- Silencing errors with
as,!orany, especiallyuseState({} as User). - Saying
React.FCis required, or that it addschildren(it hasn't since the React 18 types). - Treating types as a run-time check: a prop filled from an API response is only as correct as the response. Types describe the data; they do not verify it.
Senior signal
Talk about trade-offs rather than syntax: inference over annotations, unions only where an invalid combination is a real bug, generic components only for shared building blocks, and wrapper types in a design system that keep native props, refs and accessibility attributes flowing through. Show that you know where the checker stops: at the boundary where data enters the app.
What to check when reviewing typed React components
Yazmadığın tiplənmiş React kodunu — komanda yoldaşının pull request-ini, kitabxananın nümunəsini və ya AI assistentin təklifini — review edəndə bu siyahıdan istifadə et. Yalan danışan tip düzgün tip qədər rahat kompilyasiya olunur, ona görə bu bug-lar sonra üzə çıxır: gec gələn datada çökmə və ya heç kimin nəzərə almadığı prop birləşməsi kimi.
- Tip yoxlaması
strictaktiv olanda və yeniany,as,!və ya@ts-ignoreolmadan keçirmi? Layihənin tip yoxlamasını (tsc --noEmit) işə sal: tipləri sadəcə silən bundler tip xətaları olan kodu da build edir. Hər qaçış yolunun səbəbi olmalıdır;useState({} as User)vəref.current!üçün adətən tiplənmiş həll var. null,[]və ya sətir literalı ilə başlayan həruseState-in real dəyərləri əhatə edən tip arqumenti varmı?useState(null)heç vaxtnull-dan başqa heç nə saxlaya bilməz,useState([])never[]-dir,useState("idle")isə union nəzərdə tutulan yerdə istənilən sətri qəbul edir.- Ref-lər bağlandıqları elementin tipi ilə tiplənib və istifadədən əvvəl yoxlanırmı?
useRef<HTMLInputElement>(null)<input>-a bağlanır, handler-lər isə?.və ya açıq yoxlamadan istifadə edir; arqumentsizuseRef()React 19-un tipləri ilə kompilyasiya olunmur. - JSX-dən çıxarılmış handler-lər React-in event tipləri ilə tiplənib və
currentTarget-i oxuyurmu? DOM-unMouseEvent-i və yaanyyox,React.MouseEvent<HTMLButtonElement>;event.target-in cast-ı uşaq elementdən başlayan klikləri gizlədir. - Native element wrapper-ləri qalan props-u və
ref-i ötürür, dəyişdirilən props üçün isəOmitistifadə edirmi?...rest-in elementə çatdığını,ComponentPropsilə tiplənmiş komponentin ref-i həqiqətən haradasa yerləşdirdiyini və dəyişdirilənvaluevə yaonChange-in əvvəlcə native props-dan çıxarıldığını yoxla. - Props komponentin nəzərə almadığı birləşməni ifadə edə bilirmi? Şübhəli istifadə yerini yaz, məsələn,
onClickiləhrefvə yadefaultOpeniləopen; kompilyasiya olunursa və komponent bunun yarısına məhəl qoymursa, discriminated union və ya?: neverçatışmır. - Hər reducer-in
switch-ineveryoxlaması ilə bitirmi? Öz kompüterində action union-ına saxta üzv əlavə et: reducer yenə kompilyasiya olunursa, yeni action səssizcə nəzərə alınmayacaq.
Use this list when you review typed React code you did not write: a teammate's pull request, a library's example or an AI assistant's suggestion. A type that lies compiles as well as a correct one, so these bugs surface later, as a crash on data that arrived late or a prop combination nobody handled.
- Does the type check pass with
stricton and no newany,as,!or@ts-ignore? Run the project's type check (tsc --noEmit): a bundler that only strips types builds code with type errors. Every escape needs a reason;useState({} as User)andref.current!usually have a typed fix. - Does every
useStatethat starts withnull,[]or a string literal have a type argument for its real values?useState(null)can only ever holdnull,useState([])isnever[], anduseState("idle")accepts any string where a union was meant. - Are refs typed with the element they are attached to and checked before use?
useRef<HTMLInputElement>(null)goes on an<input>, and handlers use?.or an explicit check;useRef()without an argument does not compile with React 19's types. - Are handlers moved out of JSX typed with React's event types, reading
currentTarget?React.MouseEvent<HTMLButtonElement>, not the DOMMouseEventand notany; a cast ofevent.targethides clicks that start on a child element. - Do wrappers of native elements pass the rest props and
refthrough, withOmitfor changed props? Check that...restreaches the element, that a component typed withComponentPropsreally puts the ref somewhere, and that a changedvalueoronChangeis omitted from the native props first. - Can the props express a combination the component does not handle? Write the doubtful call site, such as
hrefwithonClickoropenwithdefaultOpen; if it compiles and the component ignores half of it, a discriminated union or?: neveris missing. - Does every reducer's
switchend in anevercheck? Add a dummy member to the action union locally: if the reducer still compiles, a new action would be silently ignored.