Datanı sərhəddə yoxlamaq
fetch, JSON.parse, storage, URL, formlar və postMessage-dən gələn data üçün tiplər niyə sadəcə vəddir; as, ! və satisfies icra zamanı niyə heç nəyi yoxlamır; datanı sərhəddə bir dəfə sxem (Zod 4) ilə necə parse etmək, yanlış datanı necə emal etmək və bundan sonra tiplərə necə etibar etmək olar.
Oxu səviyyəsi
Seçilmiş səviyyəyə qədər olan bölmələr göstərilir.
Başlamazdan əvvəl
Bu mövzu Junior səviyyəsindən başlayır.
Tiplərin sadəcə vəd olduğu yerlər
TypeScript sənin yazdığın kodu yoxlayır. Proqram işləyəndə tiplər artıq yoxdur () və dəyərin həqiqətən kodda deyilən tipdə olduğunu heç nə yoxlamır. Öz kodunun içində bu, problem deyil: kompilyator hər mənimsətməni yoxlayıb. Datanın proqramdan kənardan gəldiyi sərhəddə isə kompilyatorun yoxlayacağı heç nə yoxdur və tip başqasının yerinə yetirməli olduğu vəddir.
Data frontend tətbiqinə haradan daxil olur və DOM tipləri sənə nə verir:
await response.json():anyJSON.parse(text):anylocalStorage.getItem(key):string | null, ardınca adətənJSON.parsegəlirnew URLSearchParams(location.search).get("page"):string | nullnew FormData(form).get("qty"):FormDataEntryValue | null, yəni sətir və yaFilemessageevent-indəkievent.data(postMessage, worker-lər):any- üçüncü tərəf skriptlərinin təyin etdiyi qlobal dəyərlər: onları necə elan etmisənsə, elə
Ən təhlükəlisi any-dir. O, istənilən tipə mənimsədilə bilir, ona görə tiplənmiş koda bir dənə də xəta olmadan axır:
type Order = { id: string; total: number; status: "paid" | "shipped" };
async function loadOrder(id: string): Promise<Order> {
const response = await fetch(`/api/orders/${id}`);
return response.json(); // any, Order kimi qəbul olunur
}
const order = await loadOrder("42");
console.log(order.total.toFixed(2));Bu kod kompilyasiya olunur. API "total": "19.90"-ı sətir kimi göndərsə, sahənin adını dəyişsə və ya 404-ə { "error": "Not found" } ilə cavab versə, TypeError loadOrder-dən uzaqda, toFixed-də çıxacaq, ya da yanlış dəyər heç bir xəta olmadan ekrana düşəcək. 404 halına diqqət et: MDN qeyd edir ki, fetch() promise-i HTTP xəta statuslarında reject olmur, ona görə kod response.ok-u özü yoxlamalıdır.
URL-dən, storage-dən və formlardan gələn sətirlərin problemi daha kiçikdir. Onların tipi düzgündür (string | null), amma sətir yenə də ədədə, tarixə və ya union-ın üzvlərindən birinə çevrilməlidir və bu çevirmə uğursuz ola bilər.
Həll daha yaxşı tip yox, yoxlamadır: , yəni proqram işləyərkən dəyərə baxıb ya tiplənmiş dəyər qaytaran, ya da nəyin səhv olduğunu bildirən kod. Bu mövzunun qalan hissəsi həmin yoxlamanı sərhəddə bir dəfə yazmaq və ondan sonra tiplərə etibar etmək haqqındadır.
TypeScript checks the code you write. When the program runs, the types are gone (), and nothing checks that a value really has the type the code says. Inside your own code that is fine: the compiler has checked every assignment. At the boundary, where data comes from outside the program, the compiler has nothing to check, and the type is a promise someone else has to keep.
Where data enters a frontend app, and what the DOM types give you:
await response.json():anyJSON.parse(text):anylocalStorage.getItem(key):string | null, usually followed byJSON.parsenew URLSearchParams(location.search).get("page"):string | nullnew FormData(form).get("qty"):FormDataEntryValue | null, a string or aFileevent.datain amessageevent (postMessage, workers):any- globals set by third-party scripts: whatever you declared them to be
any is the dangerous one. It is assignable to every type, so it flows into typed code without a single error:
type Order = { id: string; total: number; status: "paid" | "shipped" };
async function loadOrder(id: string): Promise<Order> {
const response = await fetch(`/api/orders/${id}`);
return response.json(); // any, accepted as Order
}
const order = await loadOrder("42");
console.log(order.total.toFixed(2));This compiles. If the API sends "total": "19.90" as a string, renames the field, or answers a 404 with { "error": "Not found" }, the TypeError appears in toFixed, far from loadOrder, or a wrong value reaches the screen without any error. Note the 404 case: MDN points out that a fetch() promise does not reject on HTTP error statuses, so the code has to check response.ok itself.
Strings from the URL, storage and forms have a smaller problem. Their type is honest (string | null), but the string still has to become a number, a date or one of your union members, and that conversion can fail.
The fix is not a better type but a check: , code that looks at the value while the program runs and either produces a typed value or reports what is wrong. The rest of this topic is about writing that check once, at the edge, and trusting the types after it.
as yoxlama deyil, iddiadır
kompilyatora deyir: "bu dəyəri bu tipdə say". TypeScript handbook-u bunu açıq yazır: assertion-lar kompilyasiya zamanı silinir, icra zamanı heç bir yoxlama yoxdur və assertion səhv olsa da exception atılmır.
type ViewSettings = { pageSize: number; view: "grid" | "list" };
const settings = JSON.parse(localStorage.getItem("view-settings") ?? "{}") as ViewSettings;
// Kompilyasiya olunur. Storage-də {"pageSize":"20"} varsa, bu, "205" sətridir
const next = settings.pageSize + 5;Assertion-ların dürüst istifadələri də var, yəni sənin kompilyatordan çox bildiyin yerlər: məsələn, öz HTML-inin təyin etdiyi element üçün document.getElementById("chart") as HTMLCanvasElement. Dəyər kənardan gələn hər yerdə isə onlar yanlışdır.
TypeScript bəzi assertion-ları rədd edir: o, tipi yalnız daha konkret və ya daha ümumi versiyasına çevirməyə icazə verir. "42" as number xətadır ("neither type sufficiently overlaps"). Bu qaydadan yan keçmək asandır və yan keçmə review-da aydın xəbərdarlıq işarəsidir:
// Xəta: 'string' tipinin 'number' tipinə çevrilməsi səhv ola bilər
const a = "42" as number;
// Kompilyasiya olunur: əvvəl unknown-a, sonra istənilən tipə. b yenə "42" sətridir
const b = "42" as unknown as number;as unknown as T (və ya as any as T) "kompilyatorun razı olmadığını bilirəm" deməkdir. Test köməkçisində bəzən doğru ola bilər; tətbiq kodunda isə demək olar ki, həmişə çatışmayan çevirməni və ya çatışmayan yoxlamanı gizlədir. Sərhəddə isə üst-üstə düşmə qaydası onsuz da heç nəyi qorumur: any istənilən tiplə üst-üstə düşür, ona görə JSON.parse(text) as User həmişə kompilyasiya olunur.
Gizli assertion-lar
Bəzi kodlar as yazmadan assertion edir:
async function getJson<T>(url: string): Promise<T> {
const response = await fetch(url);
return response.json();
}
const user = await getJson<User>("/api/me"); // heç nə yoxlanmırT yalnız qaytarma tipində görünür, ona görə onu çağıran seçir və heç nə onu data ilə bağlamır: daha gözəl sintaksisli as. Üçüncü tərəf skriptinin window xassəsini tipləyən declare global bloku və JSON.parse(text) as T-ni gizlədən storage köməkçisi də eynidir. Onların hər birinə əslində olduğu kimi, yəni yoxlanmamış iddia kimi yanaş və onları yoxlama aparan kodun yanında saxla.
A tells the compiler "treat this value as this type". The TypeScript handbook is explicit: assertions are removed at compile time, there is no runtime check, and no exception is thrown if the assertion is wrong.
type ViewSettings = { pageSize: number; view: "grid" | "list" };
const settings = JSON.parse(localStorage.getItem("view-settings") ?? "{}") as ViewSettings;
// Compiles. If storage holds {"pageSize":"20"}, this is the string "205"
const next = settings.pageSize + 5;Assertions have honest uses, where you know more than the compiler can: document.getElementById("chart") as HTMLCanvasElement for an element your own HTML defines, for example. They are wrong wherever the value comes from outside.
TypeScript does reject some assertions: it only allows converting to a more specific or a less specific version of a type. "42" as number is an error ("neither type sufficiently overlaps"). The rule is easy to get around, and the workaround is a clear warning sign in a review:
// Error: conversion of type 'string' to type 'number' may be a mistake
const a = "42" as number;
// Compiles: first to unknown, then to anything. b is still the string "42"
const b = "42" as unknown as number;as unknown as T (or as any as T) means "I know the compiler disagrees". It is occasionally right in a test helper; in application code it almost always hides a missing conversion or a missing check. And at the boundary the overlap rule protects nothing anyway: any overlaps with every type, so JSON.parse(text) as User always compiles.
Assertions in disguise
Some code asserts without writing as:
async function getJson<T>(url: string): Promise<T> {
const response = await fetch(url);
return response.json();
}
const user = await getJson<User>("/api/me"); // nothing is checkedT appears only in the return type, so the caller picks it and nothing connects it to the data: an as with nicer syntax. The same goes for a declare global block that types a third-party script's window property, and for a storage helper that hides JSON.parse(text) as T. Treat each of them as what it is, an unchecked claim, and keep it next to code that checks.
Annotasiya, satisfies və as
Kodda yazdığın dəyərə tip bağlamağın üç yolu var, ən sərtdən ən yumşağa doğru:
type Route = { path: string; auth: boolean };
// Annotasiya: dəyər uyğun gəlməlidir, dəyişən isə məhz bu tipi alır
const routes: Record<string, Route> = {
home: { path: "/", auth: false },
account: { path: "/account", auth: true },
};
const typo = routes.acount; // xəta yoxdur: istənilən sətir açarına icazə var
// satisfies: dəyər uyğun gəlməlidir, dəyişən isə öz, daha dar tipini saxlayır
const routes2 = {
home: { path: "/", auth: false },
account: { path: "/account", auth: true },
} satisfies Record<string, Route>;
// Xəta: 'acount' xassəsi yoxdur
const typo2 = routes2.acount;
// as: yalnız tiplərin üst-üstə düşdüyünü yoxlayır
const home = { path: "/" } as Route; // kompilyasiya olunur; icra zamanı home.auth undefined-dir- Annotasiya dəyəri tipə qarşı yoxlayır, sonra isə dəyəri unudur: dəyişən məhz annotasiyadakı tipi daşıyır, ona görə yuxarıdakı açarlar "istənilən sətir" olur.
satisfies(TypeScript 4.9) dəyəri tipə qarşı yoxlayır və çıxarılmış tipi saxlayır: açarlarhomevəaccountkimi qalır,"dark"kimi literal dəyərlər literal qalır, çatışmayan və artıq xassələr isə yenə xətadır.astiplərdən biri digərinə mənimsədilə bildikcə tipdən az xassəsi olan dəyəri qəbul edir.home-unauth-suz qalması da belə olur.
Onların heç biri icra zamanı heç nə yoxlamır. satisfies mənbə kodunda yazılmış dəyərlər üçündür; JSON.parse-a kömək edə bilməz, çünki o dəyər proqram işə düşənə qədər mövcud deyil. Kənardan gələn dataya icra zamanı işləyən kod lazımdır.
Sadə qayda: funksiya parametrlərinə və qaytarma tiplərinə annotasiya yaz; dəqiq formasını saxlamaq istədiyin literal obyektlər, məsələn, konfiqurasiya, axtarış cədvəlləri və route xəritələri üçün satisfies istifadə et; as-ı isə həqiqətən kompilyatordan çox bildiyin nadir hal üçün saxla və səbəbini şərhdə yaz.
There are three ways to attach a type to a value you write in code, from strictest to loosest:
type Route = { path: string; auth: boolean };
// Annotation: the value must match, and the variable gets exactly this type
const routes: Record<string, Route> = {
home: { path: "/", auth: false },
account: { path: "/account", auth: true },
};
const typo = routes.acount; // no error: any string key is allowed
// satisfies: the value must match, and the variable keeps its own, narrower type
const routes2 = {
home: { path: "/", auth: false },
account: { path: "/account", auth: true },
} satisfies Record<string, Route>;
// Error: property 'acount' does not exist
const typo2 = routes2.acount;
// as: only checks that the types overlap
const home = { path: "/" } as Route; // compiles; home.auth is undefined at run time- An annotation checks the value against the type and then forgets the value: the variable has exactly the annotated type, so the keys above become "any string".
satisfies(TypeScript 4.9) checks the value against the type and keeps the inferred type: the keys stayhomeandaccount, literal values such as"dark"stay literal, and missing or extra properties are still errors.asaccepts a value with fewer properties than the type, as long as one type is assignable to the other. That is howhomeends up withoutauth.
None of them checks anything at run time. satisfies is about values written in the source; it cannot help with JSON.parse, because that value does not exist until the program runs. Data from outside needs run-time code.
A rule of thumb: annotate function parameters and return types; use satisfies for literal objects whose exact shape you want to keep, such as configuration, lookup tables and route maps; keep as for the rare case where you really know more than the compiler, with a comment that says why.
Validate etmə, parse et
Bu ideyaya ad Alexis King-in 2019-da yazdığı "Parse, don't validate" məqaləsindən gəlir. Validator datanı yoxlayır və "hə" və ya "yox" cavabı verir, kodun qalanı isə yoxlanmamış tiplə işləməyə davam edir. Parser isə onun sözləri ilə "daha az strukturlu girişi qəbul edib daha strukturlu nəticə verir", ya da uğursuz olur. TypeScript dilində: unknown və ya sətir qəbul et, tiplənmiş dəyər qaytar.
// Validate edir: çağıranda hələ də sətir qalır və onu haradasa yenidən çevirir
function isValidPage(value: string | null): boolean {
return value !== null && /^[1-9]\d*$/.test(value);
}
// Parse edir: çağıran düzgün olduğu bilinən ədəd alır
function parsePage(value: string | null): number {
if (value === null) return 1;
if (!/^[1-9]\d*$/.test(value)) throw new RangeError(`Invalid page: ${value}`);
return Number(value);
}isValidPage true qaytarandan sonra kodda yenə sətir qalır və onu istifadə edən hər yer onu yenidən, bəlkə də fərqli şəkildə çevirir. parsePage-dən sonra isə yalnız ədəd var. Yoxlamanın baş verdiyinin sübutu tiplə birlikdə ötürülür.
Obyektlər üçün any-dən yox, həmişə unknown-dan başla. unknown olanda TypeScript hər müraciəti yoxlamadan keçirməyə məcbur edir ():
type Line = { sku: string; qty: number };
function parseLine(input: unknown): Line {
if (typeof input !== "object" || input === null) {
throw new TypeError("line: expected an object");
}
if (!("sku" in input) || typeof input.sku !== "string") {
throw new TypeError("line.sku: expected a string");
}
if (!("qty" in input) || typeof input.qty !== "number" || !Number.isInteger(input.qty) || input.qty < 1) {
throw new TypeError("line.qty: expected an integer >= 1");
}
return { sku: input.sku, qty: input.qty };
}Funksiya yalnız məlum sahələri olan yeni obyekt qaytarır, ona görə serverdən gələn artıq data irəli sızmır.
Bu işləyir, amma tez böyüyür: iç-içə obyektlər, massivlər, optional sahələr, yalnız birinci xəta yox, bütün xətalar, üstəlik əl ilə sinxron saxladığın tip və yoxlamalar dəsti. -ın (input is Line) da eyni zəifliyi var: gövdəsi tipinin vəd etdiyindən az yoxlayırsa, o da as kimi yalan danışır, kompilyator isə ona etibar edir. Ona görə layihələrin çoxu həm yoxlamanı, həm də tipi bir tərifdən çıxaran sxem kitabxanasından istifadə edir.
Alexis King's 2019 article "Parse, don't validate" gave the idea its name. A validator checks data and answers yes or no, and the rest of the code keeps working with the unchecked type. A parser, in her words, "consumes less-structured input and produces more-structured output", or fails. In TypeScript terms: take unknown or a string, return a typed value.
// Validates: the caller still holds a string and converts it again somewhere
function isValidPage(value: string | null): boolean {
return value !== null && /^[1-9]\d*$/.test(value);
}
// Parses: the caller gets a number that is known to be valid
function parsePage(value: string | null): number {
if (value === null) return 1;
if (!/^[1-9]\d*$/.test(value)) throw new RangeError(`Invalid page: ${value}`);
return Number(value);
}After isValidPage returns true, the code still holds a string, and each place that uses it converts it again, maybe differently. After parsePage there is only a number. The proof that the check happened travels in the type.
For objects, start from unknown, never from any. With unknown, TypeScript forces every access through a check ():
type Line = { sku: string; qty: number };
function parseLine(input: unknown): Line {
if (typeof input !== "object" || input === null) {
throw new TypeError("line: expected an object");
}
if (!("sku" in input) || typeof input.sku !== "string") {
throw new TypeError("line.sku: expected a string");
}
if (!("qty" in input) || typeof input.qty !== "number" || !Number.isInteger(input.qty) || input.qty < 1) {
throw new TypeError("line.qty: expected an integer >= 1");
}
return { sku: input.sku, qty: input.qty };
}The function returns a new object with only the known fields, so extra data from the server does not leak further.
This works, but it grows quickly: nested objects, arrays, optional fields, every error instead of the first, and a type and a set of checks that you keep in sync by hand. A (input is Line) has the same weakness: if its body checks less than its type promises, it lies exactly like as, and the compiler trusts it. That is why most projects use a schema library, which derives both the check and the type from one definition.
Zod 4 ilə sxemlər
Sxem kitabxanası gözlənilən formanı bir dəfə, dəyər kimi təsvir edir. İcra zamanı datanı bu dəyərə qarşı parse edir, kompilyasiya zamanı isə sənə tipi verir. Zod geniş yayılmış seçimdir və nümunələr Zod 4-dən istifadə edir (import * as z from "zod").
import * as z from "zod";
const Order = z.object({
id: z.string(),
total: z.number().nonnegative(),
status: z.enum(["paid", "shipped", "cancelled"]),
customerEmail: z.email(),
note: z.string().optional(),
});
type Order = z.infer<typeof Order>;
// { id: string; total: number; status: "paid" | "shipped" | "cancelled";
// customerEmail: string; note?: string | undefined }Order.parse(data)tiplənmiş dəyər qaytarır və yaZodErroratır. Dəyər yeni obyektdir (zod.dev: dərin klon), sxemin sadalamadığı açarlar isə default halda silinir.Order.safeParse(data)xəta atmır. O,{ success: true, data }və ya{ success: false, error }qaytarır, bu, discriminated union-dır,error.issuesisə hər problemipathvəmessageilə sadalayır.- Zod 4-də sətir formatları üst səviyyəli funksiyalardır (
z.email(),z.url(),z.uuid()); köhnəz.string().email()hələ işləyir, amma deprecated-dir.
async function loadOrder(id: string): Promise<Order> {
const response = await fetch(`/api/orders/${id}`);
if (!response.ok) throw new Error(`GET /api/orders/${id}: HTTP ${response.status}`);
return Order.parse(await response.json());
}URL-dən və ya formdan gələn sətirləri əvvəlcə çevirmək lazımdır. z.coerce.number() yoxlamadan əvvəl Number(input) işlədir:
const ListParams = z.object({
page: z.coerce.number().int().min(1).default(1),
sort: z.enum(["newest", "price"]).catch("newest"),
});
const params = ListParams.parse(Object.fromEntries(new URLSearchParams(location.search)));
// ?page=3&sort=name nəticədə { page: 3, sort: "newest" } verir.default(1) açar olmayanda tətbiq olunur. .catch("newest") uğursuz olmaq əvəzinə yanlış dəyəri əvəz edir, bu da insanların əl ilə dəyişdiyi URL parametrlərinə yaraşır. Number()-in nə etdiyinə diqqət et: boş ?page= 0 olur (burada .min(1) onu rədd edir).
Transform-lar nəticənin tipini dəyişir: z.iso.datetime().transform((s) => new Date(s)) ISO sətri qəbul edir və Date verir. z.input<typeof S> və z.output<typeof S> iki tərəfi adlandırır; z.infer nəticə tipidir.
A schema library describes the expected shape once, as a value. At run time it parses data against that value; at compile time it gives you the type. Zod is a common choice, and the examples use Zod 4 (import * as z from "zod").
import * as z from "zod";
const Order = z.object({
id: z.string(),
total: z.number().nonnegative(),
status: z.enum(["paid", "shipped", "cancelled"]),
customerEmail: z.email(),
note: z.string().optional(),
});
type Order = z.infer<typeof Order>;
// { id: string; total: number; status: "paid" | "shipped" | "cancelled";
// customerEmail: string; note?: string | undefined }Order.parse(data)returns a typed value or throws aZodError. The value is a new object (zod.dev: a deep clone), and keys the schema does not list are stripped by default.Order.safeParse(data)does not throw. It returns{ success: true, data }or{ success: false, error }, a discriminated union, anderror.issueslists every problem with itspathandmessage.- In Zod 4 string formats are top-level functions (
z.email(),z.url(),z.uuid()); the olderz.string().email()still works but is deprecated.
async function loadOrder(id: string): Promise<Order> {
const response = await fetch(`/api/orders/${id}`);
if (!response.ok) throw new Error(`GET /api/orders/${id}: HTTP ${response.status}`);
return Order.parse(await response.json());
}Strings from the URL or a form need converting first. z.coerce.number() runs Number(input) before checking:
const ListParams = z.object({
page: z.coerce.number().int().min(1).default(1),
sort: z.enum(["newest", "price"]).catch("newest"),
});
const params = ListParams.parse(Object.fromEntries(new URLSearchParams(location.search)));
// ?page=3&sort=name gives { page: 3, sort: "newest" }.default(1) applies when the key is missing. .catch("newest") replaces an invalid value instead of failing, which suits URL parameters people edit by hand. Mind what Number() does: an empty ?page= becomes 0 (rejected here by .min(1)).
Transforms change the output type: z.iso.datetime().transform((s) => new Date(s)) accepts an ISO string and gives a Date. z.input<typeof S> and z.output<typeof S> name the two sides; z.infer is the output.
Yanlış datanı necə emal etməli
Parse etmək yalnız uğursuzluq qəsdən emal olunanda kömək edir, düzgün reaksiya isə datanın haradan gəldiyindən asılıdır.
API cavabları: mənbəyə yaxın yerdə açıq-aşkar xəta ver. Sxemə uyğun gəlməyən cavab ya bug-dır, ya da client ilə server arasındakı müqavilənin dəyişməsidir. Sərhəddə endpoint-i və problemləri adlandıran mesajla xəta at, xəta vəziyyətini error boundary və ya data kitabxanası göstərsin, xətanı da report et. Yanlış olduğunu bildiyin datadan səhifənin yarısını render etmək daha pisdir.
async function getJson<T>(url: string, schema: z.ZodType<T>): Promise<T> {
const response = await fetch(url);
if (!response.ok) throw new Error(`${url}: HTTP ${response.status}`);
const result = schema.safeParse(await response.json());
if (!result.success) {
throw new Error(`${url}: unexpected response\n${z.prettifyError(result.error)}`);
}
return result.data;
}Burada T sxemə bağlıdır, ona görə qaytarma tipi iddia yox, qazanılmış nəticədir. z.prettifyError problemləri "✖ Invalid input: expected number, received string → at total" kimi sətirlərə çevirir.
Saxlanmış data: ehtiyat dəyərə keç. localStorage-dəki datanı tətbiqin köhnə versiyası yaza və ya kimsə əl ilə dəyişə bilər. Onu parse et, uğursuz olsa, default dəyərlərdən istifadə et: istifadəçi səhifəni yox, bir seçimini itirir.
const ViewSettings = z.object({ pageSize: z.int().min(10).max(100), view: z.enum(["grid", "list"]) });
const DEFAULT_VIEW = { pageSize: 20, view: "grid" } satisfies z.infer<typeof ViewSettings>;
function readViewSettings(): z.infer<typeof ViewSettings> {
try {
const result = ViewSettings.safeParse(JSON.parse(localStorage.getItem("view-settings") ?? "null"));
return result.success ? result.data : DEFAULT_VIEW;
} catch {
return DEFAULT_VIEW; // JSON.parse səhv formatlı mətndə xəta atır
}
}İstifadəçi daxiletməsi: problemləri göstər. Formda problemləri sahələrə bağla: z.flattenError(error).fieldErrors { email: ["Enter a valid email"] } verir, öz mesajların isə error parametrinə yazılır, məsələn, z.email({ error: "Enter a valid email" }). Serverdə də yoxla: client tərəfdəki yoxlama istifadəçinin rahatlığı üçündür və server ona etibar edə bilməz.
Başqa pəncərələrdən gələn mesajlar: əvvəlcə göndərəni yoxla. MDN-in postMessage üçün məsləhəti event.origin-i yoxlamaq, sonra isə mesajın sintaksisini yenə də yoxlamaqdır. Uyğun gəlməyəni at.
Səssiz ara yoldan qaç: API cavabının hər sahəsinə .catch() və ya ?? 0 qoymaq pozulmuş müqaviləni log-larda heç bir iz olmadan ekranda yanlış rəqəmlərə çevirir.
Parsing helps only if failure is handled on purpose, and the right reaction depends on where the data came from.
API responses: fail loudly, close to the source. A response that does not match the schema is a bug or a contract change between client and server. Throw at the boundary with a message that names the endpoint and the issues, let the error boundary or the data library show an error state, and report it. Rendering half a page from data you know is wrong is worse.
async function getJson<T>(url: string, schema: z.ZodType<T>): Promise<T> {
const response = await fetch(url);
if (!response.ok) throw new Error(`${url}: HTTP ${response.status}`);
const result = schema.safeParse(await response.json());
if (!result.success) {
throw new Error(`${url}: unexpected response\n${z.prettifyError(result.error)}`);
}
return result.data;
}Here T is tied to the schema, so the return type is earned, not claimed. z.prettifyError turns the issues into lines like "✖ Invalid input: expected number, received string → at total".
Stored data: fall back. What sits in localStorage may have been written by an older version of the app or edited by hand. Parse it, and if that fails, use defaults: the user loses a preference, not the page.
const ViewSettings = z.object({ pageSize: z.int().min(10).max(100), view: z.enum(["grid", "list"]) });
const DEFAULT_VIEW = { pageSize: 20, view: "grid" } satisfies z.infer<typeof ViewSettings>;
function readViewSettings(): z.infer<typeof ViewSettings> {
try {
const result = ViewSettings.safeParse(JSON.parse(localStorage.getItem("view-settings") ?? "null"));
return result.success ? result.data : DEFAULT_VIEW;
} catch {
return DEFAULT_VIEW; // JSON.parse throws on malformed text
}
}User input: show the issues. For a form, map the issues to fields: z.flattenError(error).fieldErrors gives { email: ["Enter a valid email"] }, and custom messages go in the error parameter, as in z.email({ error: "Enter a valid email" }). Validate on the server as well: the client-side check is for the user's convenience, and the server cannot trust it.
Messages from other windows: check the sender first. MDN's advice for postMessage is to verify event.origin and then still verify the syntax of the message. Drop what does not match.
Avoid the quiet middle ground: .catch() or ?? 0 on every field of an API response turns a broken contract into wrong numbers on the screen, with nothing in the logs.
Digər yoxlanmamış iddialar: !, definite assignment, guard-lar
as kompilyatora onun yoxlaya bilmədiyi nəyisə deməyin yeganə yolu deyil. Bunların hamısı da icra zamanı yox olur.
Non-null assertion !. value! tipdən null və undefined-i çıxarır; handbook onu mahiyyətcə type assertion adlandırır. Sərhəddə o, çatışmayan dəyəri səssiz bug-a çevirir:
const orderId = new URLSearchParams(location.search).get("order")!;
// URL-də ?order= yoxdursa, bu, /api/orders/null sorğusu göndərir
fetch(`/api/orders/${orderId}`);Template literal-ın içində null "null" mətninə çevrilir, ona görə aydın xəta əvəzinə tətbiq serverdən mövcud olmayan sifarişi istəyir. Yoxla və bu halı emal et: if (!orderId) return showNotFound();.
Definite assignment !:. let config!: Config və ya client!: ApiClient klass sahəsi TypeScript-ə deyir ki, dəyər kimsə onu oxumazdan əvvəl təyin olunacaq, ona görə o, "used before being assigned" yoxlamasını etmir:
let config!: { apiUrl: string };
export function initConfig(apiUrl: string) {
config = { apiUrl };
}
export function ordersUrl() {
return `${config.apiUrl}/orders`; // initConfig hələ işləməyibsə, TypeError
}Çağırışların sırası dəyişsə, config undefined olur. Onu elan edərkən ilkin dəyər ver, parametr kimi ötür və ya Config | undefined kimi tiplə və yoxla.
Vəd etdiyindən az yoxlayan type guard-lar.
function isOrder(x: unknown): x is Order {
return typeof x === "object" && x !== null && "id" in x;
}isOrder(data)-dan sonra kompilyator data-nı tam Order sayır, halbuki yalnız id yoxlanıb. Bu predikat funksiyaya bükülmüş assertion-dır.
Qlobal dəyərlər üçün elanlar. Üçüncü tərəf skriptinin window-a yazdığı xassə üçün declare global yazısı nəzarət etmədiyin kod barədə vəddir; skript bloklana və ya hələ yüklənməmiş ola bilər. Onu optional kimi tiplə və çağırmazdan əvvəl yoxla.
İndeksləmə. noUncheckedIndexedAccess olmadan items[0] və byId[key] olmayanda da mövcud kimi tiplənir. Bu seçim aktiv olanda onların tipinə undefined daxil olur.
Review-da dayanmalı olduğun yerlər bunlardır: !., !:, x is T, declare global və as. Onların hər birinin yalnız kompilyasiya zamanı yox, icra zamanı da doğru qalan səbəbi olmalıdır.
as is not the only way to tell the compiler something it cannot verify. All of these vanish at run time too.
The non-null assertion !. value! removes null and undefined from the type; the handbook calls it effectively a type assertion. At the boundary it turns a missing value into a silent bug:
const orderId = new URLSearchParams(location.search).get("order")!;
// Without ?order= in the URL this requests /api/orders/null
fetch(`/api/orders/${orderId}`);null inside a template literal becomes the text "null", so instead of a clear error the app asks the server for an order that does not exist. Check and handle it: if (!orderId) return showNotFound();.
Definite assignment !:. let config!: Config or a class field client!: ApiClient tells TypeScript the value will be set before anyone reads it, so it skips the "used before being assigned" check:
let config!: { apiUrl: string };
export function initConfig(apiUrl: string) {
config = { apiUrl };
}
export function ordersUrl() {
return `${config.apiUrl}/orders`; // TypeError if initConfig has not run yet
}If the order of calls changes, config is undefined. Initialise at the declaration, pass the value as a parameter, or type it Config | undefined and check.
Type guards that check less than they promise.
function isOrder(x: unknown): x is Order {
return typeof x === "object" && x !== null && "id" in x;
}After isOrder(data) the compiler treats data as a complete Order, although only id was checked. The predicate is an assertion with a function around it.
Declarations for globals. A declare global entry for a property that a third-party script sets on window is a promise about code you do not control; the script may be blocked or not loaded yet. Type it as optional and check before calling it.
Indexing. Without noUncheckedIndexedAccess, items[0] and byId[key] are typed as present even when they are not. With the flag on, their type includes undefined.
In review, these are the places to stop: !., !:, x is T, declare global and as. Each one needs a reason that holds at run time, not just at compile time.
Bir dəfə, sərhəddə yoxla
Validasiyanın yeri datanın proqrama daxil olduğu yerdir və yalnız oradır. İçəridə tiplər doğrudur, çünki kompilyator hər addımı yoxlayıb; hər komponentdə yenidən yoxlamaq kod və vaxt aparır, növbəti oxucuya isə heç kimin tiplərə etibar etmədiyini deyir.
Tətbiqi nazik sərhədin içindəki tiplənmiş nüvə kimi təsəvvür et:
fetch, storage, URL, form, postMessage
| unknown, any or string
v
edge: parse with a schema --fail--> error state, report, fallback
| Order, ViewSettings, ListParams
v
typed core: components, hooks, state (no casts, no re-checks)Praktikada bu nə deməkdir:
fetch-in sahibi bir API moduludur. Hər endpoint funksiyası parse olunmuş data qaytarır, məsələn,getJson(url, Order), komponentlər isəresponse.json()-u özləri heç vaxt çağırmır. TanStack Query kimi data kitabxanası ilə parse-ı query funksiyasının içində et ki, keşdə yalnız düzgün data saxlanılsın.JSON.parsevəgetstorage və URL köməkçilərinə aiddir.readViewSettings()və yauseListParams()hook-u tiplənmiş dəyərlər qaytarır; xam sətirlərə başqa heç nə toxunmur.- Tiplər sxemlərdən gəlir. Sxemin yanında əl ilə yazılmış tip əvəzinə
type Order = z.infer<typeof Order>: eyni formanın iki tərifi zamanla bir-birindən ayrılır. - Generasiya olunmuş tiplər də vəddir. API təsvirindən generasiya olunan və ya TypeScript backend-i ilə ortaq istifadə olunan tiplər serverin nə göndərməli olduğunu təsvir edir. İşləyən server deploy ardıcıllığı, proxy-nin xəta səhifəsi və ya keşdə qalmış köhnə cavab üzündən yenə də fərqli ola bilər, ona görə cavablar yenə sərhəddə parse olunur.
- Hər mənbənin öz reaksiyası var. API cavabları açıq-aşkar xəta verir, saxlanmış data default-lara keçir, istifadəçi daxiletməsi mesaj göstərir, başqa origin-lərdən gələn mesajlar isə origin və forma uyğun gəlmirsə, atılır.
Bunun qiyməti
Parse bütün dəyəri başdan-sona yoxlayır, ona görə onun qiyməti datanın ölçüsü ilə artır. Adi cavablarda bu, şəbəkə ilə müqayisədə kiçikdir, amma hər render-də yox, hər cavab üçün bir dəfə parse et və böyük payload-u optimallaşdırmazdan əvvəl ölç. Bundle ölçüsü də önəmlidir: Zod Mini (zod/mini) Zod-un funksional API-li, tree-shaking-ə uyğun variantıdır və hər kilobaytın vacib olduğu səhifələr üçündür.
Nəticədə as və ! elə nadir olur ki, dərhal gözə çarpır. Nüvədəki dəyərin tipi varsa, o tipi ya kompilyator hesablayıb, ya da parser yaradıb, arada isə heç nə səndən ona sadəcə inanmağı istəmir.
Validation belongs where data enters the program, and only there. Inside, the types are true because the compiler checked every step; checking again in each component costs code and time, and tells the next reader that nobody trusts the types.
Picture the app as a typed core inside a thin edge:
fetch, storage, URL, form, postMessage
| unknown, any or string
v
edge: parse with a schema --fail--> error state, report, fallback
| Order, ViewSettings, ListParams
v
typed core: components, hooks, state (no casts, no re-checks)What that means in practice:
- One API module owns
fetch. Every endpoint function returns parsed data, as ingetJson(url, Order), and components never callresponse.json()themselves. With a data library such as TanStack Query, parse inside the query function, so the cache only ever holds valid data. - Storage and URL helpers own
JSON.parseandget.readViewSettings()or auseListParams()hook returns typed values; nothing else touches the raw strings. - Types come from the schemas.
type Order = z.infer<typeof Order>instead of a hand-written type next to the schema: two definitions of one shape drift apart. - Generated types are still a promise. Types generated from an API description, or shared with a TypeScript backend, describe what the server should send. The running server can still differ, because of a deploy order, a proxy error page or an old cached response, so responses are still parsed at the edge.
- Each source gets its own reaction. API responses fail loudly, stored data falls back to defaults, user input shows messages, and messages from other origins are dropped unless the origin and the shape match.
What it costs
Parsing walks the whole value, so its cost grows with the size of the data. For typical responses it is small next to the network, but parse once per response, not on every render, and measure before optimising a large payload. Bundle size counts too: Zod Mini (zod/mini) is a tree-shakable variant of Zod with a functional API, for pages where every kilobyte matters.
The payoff is a codebase where as and ! are rare enough to stand out. When a value inside the core has a type, that type was either computed by the compiler or produced by a parser, and nothing in between asks you to believe it.
Data dəyişəndə sxemlər
Sərhəddəki data dəyişir. Server yeni sahə əlavə edir və ya birinin adını dəyişir, tətbiqinin köhnə versiyası isə storage-ə başqa formada yazıb. Belə olanda nə baş verəcəyinə sxem qərar verir.
Naməlum açarlar. z.object sadalamadığı açarları silir, ona görə serverdən gələn yeni sahəyə məhəl qoyulmur və heç nə pozulmur. z.strictObject naməlum açarları rədd edir: konfiqurasiya faylı kimi tam sənə məxsus data üçün doğrudur, amma API cavablarında serverdəki hər əlavəni client-də uğursuzluğa çevirir. z.looseObject naməlum açarları saxlayır və onun tipi onlara icazə verir.
Versiyalı saxlanmış data. Datanın yanında versiya nömrəsi saxla, discriminated union ilə parse et, sonra cari formaya miqrasiya et:
const SettingsV1 = z.object({ version: z.literal(1), compact: z.boolean() });
const SettingsV2 = z.object({ version: z.literal(2), density: z.enum(["compact", "comfortable"]) });
const StoredSettings = z.discriminatedUnion("version", [SettingsV1, SettingsV2]);
function migrate(stored: z.infer<typeof StoredSettings>): z.infer<typeof SettingsV2> {
if (stored.version === 2) return stored;
return { version: 2, density: stored.compact ? "compact" : "comfortable" };
}Heç bir versiyaya uyğun gəlməyən data default-lara keçir. Versiya sahəsi olmadan hansı formanı oxuduğunu ancaq təxmin edə bilərsən.
null, undefined və olmayan açar. JSON-da null var, undefined isə yoxdur. "note": null göndərən API z.string().optional()-dan keçmir, çünki o, yalnız undefined-i və ya olmayan açarı qəbul edir. null üçün .nullable(), hər ikisi üçün .nullish() istifadə et və kodun qalanının ümumiyyətlə null görüb-görməməli olduğuna qərar ver; sərhəddəki transform onu bir dəfə undefined-ə çevirə bilər.
Giriş və nəticə tipləri. Coercion, transform və default-lar olanda gələn data (z.input) ilə kodunun saxladığı data (z.output) fərqlənir: formun girişində sətirlər, nəticəsində isə ədədlər və tarixlər olur. Xam tərəflə işləyən funksiyalara, məsələn, test fixture-larına və ya formun ilkin dəyərlərinə giriş tipi lazımdır.
Mock-lar da köhnəlir. API cavabının əl ilə yazılmış mock-u real API dəyişəndən sonra da keçməyə davam edir. Fixture-lar eyni sxemlərlə parse olunursa və ya z.input<typeof Order> kimi tiplənibsə, sxem dəyişən kimi köhnəlmiş fixture uğursuz olur. Beləliklə sxem müqaviləni həm kodun, həm də testlərin oxuduğu bir yerdə sənədləşdirir.
Zod 4 burada Zod 3 ilə müqayisədə bəzi detalları dəyişib, məsələn, .default() undefined-də parse-ı dərhal dayandırır, z.coerce sxemlərinin giriş tipi isə unknown olub. Versiyanı yeniləyəndə yaddaşa güvənmə, zod.dev-dəki miqrasiya bələdçisini oxu.
Data at the boundary changes. The server adds a field or renames one, and an older version of your app wrote storage in another shape. The schema decides what happens then.
Unknown keys. z.object strips keys it does not list, so a new field from the server is ignored and nothing breaks. z.strictObject rejects unknown keys: right for data you fully own, like a configuration file, but for API responses it turns every additive change on the server into a failure in the client. z.looseObject keeps unknown keys, and its type allows them.
Stored data with versions. Store a version number with the data, parse with a discriminated union, then migrate to the current shape:
const SettingsV1 = z.object({ version: z.literal(1), compact: z.boolean() });
const SettingsV2 = z.object({ version: z.literal(2), density: z.enum(["compact", "comfortable"]) });
const StoredSettings = z.discriminatedUnion("version", [SettingsV1, SettingsV2]);
function migrate(stored: z.infer<typeof StoredSettings>): z.infer<typeof SettingsV2> {
if (stored.version === 2) return stored;
return { version: 2, density: stored.compact ? "compact" : "comfortable" };
}Anything that matches neither version falls back to defaults. Without the version field you can only guess which shape you are reading.
null, undefined and missing. JSON has null but no undefined. An API that sends "note": null fails z.string().optional(), which accepts only undefined or a missing key. Use .nullable() for null, or .nullish() for both, and decide whether the rest of the code should see null at all; a transform at the edge can turn it into undefined once.
Input and output types. With coercion, transforms and defaults, what arrives (z.input) and what your code holds (z.output) differ: a form's input has strings, its output numbers and dates. Functions that handle the raw side, such as test fixtures or a form's initial values, need the input type.
Mocks drift too. A hand-written mock of an API response keeps passing after the real API changes. If fixtures are parsed with the same schemas, or typed as z.input<typeof Order>, an outdated fixture fails as soon as the schema changes. The schema then also documents the contract in one place that both the code and the tests read.
Zod 4 changed details here compared with Zod 3, such as .default() short-circuiting on undefined and the input type of z.coerce schemas becoming unknown. When you upgrade, read the migration guide on zod.dev rather than relying on memory.
Müsahibə üçün məsləhətlər
30 saniyəlik cavab. "TypeScript-in tipləri silinir, ona görə onlar yalnız kompilyatorun gördüyü datanı təsvir edir. Kənardan gələn hər şey, məsələn, fetch().json(), JSON.parse, storage, URL parametrləri, formlar və postMessage, any, unknown və ya sətir kimi gəlir, as isə sadəcə kompilyatoru susdurur. Həmin datanı sərhəddə bir dəfə sxemlə parse edirəm, məsələn, Zod ilə: o, dəyəri icra zamanı yoxlayır və tipi z.infer ilə verir. Yanlış data mənbəyə görə emal olunur: API xətaları açıq-aşkar üzə çıxarılır, saxlanmış data default-a keçir, form daxiletməsi mesaj göstərir. Sərhəddən sonra tiplərə etibar edirəm və cast-lardan qaçıram."
Gözlənilən suallar
as, annotasiya vəsatisfiesarasında fərq nədir? Annotasiya yoxlayır və annotasiyadakı tipə genişləndirir;satisfiesyoxlayır və çıxarılmış tipi saxlayır;asyalnız tiplərin üst-üstə düşməsini tələb edir. Onların heç biri icra zamanı işləmir.as unknown as Tniyə təhlükə siqnalıdır? O,as-ın yeganə yoxlamasından yan keçir. Hansı çevirmənin və ya validasiyanın çatışmadığını soruş.fetchwrapper-ini necə tipləyirsən? Gizli cast olangetJson<T>(url): Promise<T>kimi yox, sxem qəbul edib onun nəticə tipini qaytaran funksiya kimi.parse, yoxsasafeParse?parsexəta atır, bu da uğursuzluğun istisna olduğu və onu error boundary-nin emal etdiyi yerlərə yaraşır;safeParseisə formlar və storage kimi yerində reaksiya verən yerlər üçün nəticə qaytarır.- Harada validate edirsən? Bir dəfə, datanın daxil olduğu yerdə: API modulunda, storage və URL köməkçilərində, mesaj listener-lərində. Hər komponentdə yox.
!icra zamanı nə edir? Heç nə. O, yalnız tipdənnullvəundefined-i çıxarır.
Bal itirdən səhvlər
- TypeScript-in API cavablarını "validate etdiyini" və ya generic tip parametrinin
fetch-i tip baxımından təhlükəsiz etdiyini demək. - API sahə əlavə edəndə nə olacağını müzakirə etmədən üçüncü tərəf API cavabları üçün
strictObjecttəklif etmək. - Yanlış datanı hər yerdə default-larla udmaq: ekrandakı yanlış rəqəmləri debug etmək xətadan daha çətindir.
Senior səviyyəni göstərən məqamlar
Sərhəddən dizayn qərarı kimi danış: hər mənbənin sahibi hansı moduldur, sxemlər serverlə necə bölüşdürülür və ya onun təsvirindən necə generasiya olunur, fixture-lar necə sinxron saxlanılır, uğursuzluqlar necə report olunur və böyük payload-larda validasiya bundle ölçüsü və CPU vaxtı baxımından nəyə başa gəlir.
A 30-second answer. "TypeScript's types are erased, so they only describe data the compiler has seen. Anything from outside, such as fetch().json(), JSON.parse, storage, URL parameters, forms and postMessage, arrives as any, unknown or a string, and as only silences the compiler. I parse that data once at the edge with a schema, Zod for example, which checks the value at run time and gives me the type through z.infer. Invalid data is handled per source: API errors fail loudly, stored data falls back, form input shows messages. After the edge I trust the types and avoid casts."
Questions you are likely to get
- What is the difference between
as, an annotation andsatisfies? An annotation checks and widens to the annotated type;satisfieschecks and keeps the inferred type;asonly requires the types to overlap. None of them runs at run time. - Why is
as unknown as Ta red flag? It bypasses the only checkashas. Ask which conversion or validation is missing. - How do you type a
fetchwrapper? NotgetJson<T>(url): Promise<T>, which is a disguised cast, but a function that takes a schema and returns its output type. parseorsafeParse?parsethrows, which suits places where failure is exceptional and an error boundary handles it;safeParsereturns a result for places that react locally, such as forms and storage.- Where do you validate? Once, where data enters: the API module, storage and URL helpers, message listeners. Not in every component.
- What does
!do at run time? Nothing. It removesnullandundefinedfrom the type only.
Mistakes that cost points
- Saying TypeScript "validates" API responses, or that a generic type parameter makes
fetchtype-safe. - Proposing
strictObjectfor third-party API responses without discussing what happens when the API adds a field. - Swallowing invalid data with defaults everywhere: wrong numbers on screen are harder to debug than an error.
Senior signal
Talk about the boundary as a design decision: which module owns each source, how schemas are shared with the server or generated from its description, how fixtures stay in sync, how failures are reported, and what validation costs in bundle size and CPU time for large payloads.
Kənardan gələn datanı emal edən kodu review edərkən nəyi yoxlamalı
Proqramdan kənardan gələn datanı oxuyan, amma sənin yazmadığın kodu — 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. Yoxlanmamış data yoxlanmış data kimi kompilyasiya olunur, ona görə problem sonra üzə çıxır: səbəbdən uzaqda çökmə və ya ekranda yanlış dəyər kimi.
fetch,JSON.parse, storage, URL, form və yapostMessage-dən gələn hər dəyər tiplənmiş kod onu istifadə etməzdən əvvəl parser-dən keçirmi?.json(),JSON.parse,getItem(,.get(vəevent.data-nı axtar və hər dəyəri izlə: növbəti addımas, annotasiya və yaPromise<T>qaytarmasıdırsa, onun tipi yoxlanmayıb.- Hər
as,as unknown as,!və!:icra zamanı doğru olan nə iləsə əsaslandırılıbmı? Şərh iddianın niyə doğru olduğunu deməlidir;as unknown as Tvə URL parametrində və ya storage dəyərində!adətən çatışmayan yoxlama deməkdir. - Body parse olunmazdan əvvəl HTTP statusu yoxlanırmı?
fetch404 və ya 500-də də resolve olur;response.okolmadan kod xəta səhifəsini və ya xəta obyektini data kimi parse edir. - Tiplər sxemlərin yanında yazılmayıb, onlardan çıxarılırmı (
z.infer,z.input)? Eyni formanın iki tərifi zamanla ayrılır;Ordersxeminin yanında əl ilə yazılmıştype Orderaxtar. - Sətir çevirmələri qəsdən edilibmi? Boş sətrin
Number("")vəz.coerce.number()ilə çevrilməsi0verir, olmayan URL parametrinull-dur,FormData.getisəFileqaytara bilər; hər halın.min(1), default və ya xəta kimi qaydası olduğunu yoxla. - Hər uğursuzluq yolu görünən nəsə edirmi? API uyğunsuzluğu endpoint adı ilə xəta atmalı və ya report olunmalı, saxlanmış data default-lara keçməli, form xətaları isə sahələrə çatmalıdır; cavab datasında səssiz
.catch()və ya?? 0pozulmuş müqaviləni gizlədir. messagelistener-lərievent.data-nı oxumazdan əvvəlevent.origin-i yoxlayırmı? MDN-in məsləhəti əvvəlcə göndərəni, sonra mesajın sintaksisini yoxlamaqdır; origin yoxlaması olmayan listener istənilən pəncərədən data qəbul edir.
Use this list when you review code you did not write that reads data from outside the program: a teammate's pull request, a library's example or an AI assistant's suggestion. Unchecked data compiles exactly like checked data, so the problem shows up later, as a crash far from the cause or a wrong value on screen.
- Does every value from
fetch,JSON.parse, storage, the URL, a form orpostMessagepass through a parser before typed code uses it? Search for.json(),JSON.parse,getItem(,.get(andevent.data, and follow each value: if the next step isas, an annotation or aPromise<T>return, its type is unchecked. - Is every
as,as unknown as,!and!:justified by something true at run time? A comment should say why the claim holds;as unknown as Tand!on a URL parameter or a storage value usually mean a missing check. - Is the HTTP status checked before the body is parsed?
fetchresolves on a 404 or 500; withoutresponse.okthe code parses an error page or an error object as if it were data. - Are types derived from the schemas (
z.infer,z.input) instead of written next to them? Two definitions of one shape drift; look for a hand-writtentype Orderbeside anOrderschema. - Are string conversions deliberate?
Number("")andz.coerce.number()of an empty string give0, a missing URL parameter isnull, andFormData.getmay return aFile; check that each case has a rule such as.min(1), a default or an error. - Does each failure path do something visible? An API mismatch should throw or report with the endpoint named, stored data should fall back to defaults, and form errors should reach the fields; a silent
.catch()or?? 0on response data hides a broken contract. - Do
messagelisteners checkevent.originbefore readingevent.data? MDN's advice is to verify the sender and then the message's syntax; a listener without an origin check accepts data from any window.