Narrowing, type guard-lar və unknown
TypeScript union tipləri adi JavaScript yoxlamalarına (typeof, truthiness, bərabərlik, in, instanceof) əsasən necə dəqiqləşdirir, control-flow analizi onları necə izləyir və harada dayanır, unknown və tutulmuş xətalar, tamlıq yoxlaması ilə discriminated union-lar və yalan deyə bilən type guard-lar.
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.
Union tiplər və narrowing
JavaScript-də dəyərin çox vaxt birdən artıq mümkün tipi olur. Funksiya id-ni string və ya ədəd kimi qəbul edə bilər; document.querySelector element və ya null qaytarır; optional parametr ya dəyərdir, ya da undefined. TypeScript bunu | ilə union tip kimi yazır:
function formatId(id: string | number): string {
return id.toUpperCase();
// xəta: Property 'toUpperCase' does not exist on type 'string | number'.
// Property 'toUpperCase' does not exist on type 'number'.
}Union tipli dəyər onun istənilən üzvü ola bilər, ona görə TypeScript yalnız bütün üzvlərin dəstəklədiyi əməliyyatlara icazə verir. id.toString() problem deyil, çünki o, həm string-lərdə, həm də ədədlərdə var; toUpperCase isə yalnız string-lərdədir.
Bir üzvə aid hissələrdən istifadə etmək üçün adi JavaScript ilə dəyərin hansı üzv olduğunu yoxla:
function formatId(id: string | number): string {
if (typeof id === "string") {
return id.toUpperCase(); // burada id string-dir
}
return id.toFixed(0); // burada id number-dir
}if-in içində TypeScript id-nin string olduğunu bilir; ondan sonra yalnız number qalır. Elan olunmuş tipin koddakı yoxlamalara əsasən daha konkret tipə endirilməsinə (narrowing), bunu edən yoxlamalara isə deyilir. İcra zamanı yeni heç nə baş vermir: typeof id === "string" adi JavaScript-dir və TypeScript onu sənin oxuduğun kimi oxuyur.
Literal tiplərin union-ları da eyni dərəcədə geniş yayılıb:
type Theme = "light" | "dark" | "system";
function applyTheme(theme: Theme) {
if (theme === "system") {
// theme "system"-dir
} else {
// theme "light" | "dark"-dır
}
}strictNullChecks qoşulu olanda null və undefined digərləri kimi union üzvləridir: string | null dəyərində string metodunu çağırmazdan əvvəl onu daraltmaq lazımdır. Gündəlik kodda daraltmanın çoxu məhz burada baş verir: olmaya biləcək element, optional prop, find-ın nəticəsi.
Mövzunun qalan hissəsi TypeScript-in hansı yoxlamaları başa düşdüyündən, onları kodda necə izlədiyindən və harada izləməyi dayandırdığından bəhs edir.
A value in JavaScript often has more than one possible type. A function may accept an id as a string or a number; document.querySelector returns an element or null; an optional parameter is a value or undefined. TypeScript writes this as a union type, with |:
function formatId(id: string | number): string {
return id.toUpperCase();
// error: Property 'toUpperCase' does not exist on type 'string | number'.
// Property 'toUpperCase' does not exist on type 'number'.
}A value of a union type could be any of its members, so TypeScript allows only what every member supports. id.toString() is fine, because strings and numbers both have it; toUpperCase exists only on strings.
To use the parts that belong to one member, check which member you have, with ordinary JavaScript:
function formatId(id: string | number): string {
if (typeof id === "string") {
return id.toUpperCase(); // here id is string
}
return id.toFixed(0); // here id is number
}Inside the if, TypeScript knows that id is a string; after it, only number is left. Refining a declared type to a more specific one based on checks in the code is called , and the checks that do it are called . Nothing new happens at run time: typeof id === "string" is plain JavaScript, and TypeScript reads it the way you do.
Unions of literal types are just as common:
type Theme = "light" | "dark" | "system";
function applyTheme(theme: Theme) {
if (theme === "system") {
// theme is "system"
} else {
// theme is "light" | "dark"
}
}With strictNullChecks on, null and undefined are union members like any other: a string | null has to be narrowed before you call a string method on it. That is where most narrowing in everyday code happens: the element that may not exist, the optional prop, the result of find.
The rest of this topic is about which checks TypeScript understands, how it follows them through your code, and where it stops following.
typeof və truthiness yoxlamaları
typeof sabit sətirlər dəstindən birini qaytarır və TypeScript onların hər biri ilə daraldır: "string", "number", "bigint", "boolean", "symbol", "undefined", "object" və "function".
function padLeft(padding: number | string, input: string): string {
if (typeof padding === "number") {
return " ".repeat(padding) + input;
}
return padding + input;
}typeof null tələsi
JavaScript-də typeof null "object"-dir; bu, TypeScript-in də olduğu kimi modelləşdirdiyi tarixi təsadüfdür:
function printAll(items: string[] | null) {
if (typeof items === "object") {
for (const item of items) console.log(item);
// xəta: 'items' is possibly 'null'.
}
}Yoxlama items-i string[]-ə yox, string[] | null-a daraltdı. null ilə açıq müqayisə et (items !== null) və ya massivə qədər daraldan Array.isArray(items) işlət.
Truthiness
if (value) da daraldır: true budağında null və undefined qalmır. JavaScript-də falsy dəyərlər false, 0, -0, 0n, "", NaN, null və undefined-dir (üstəgəl köhnə document.all), tələ isə ondadır ki, onların bəziləri düzgün datadır:
function unreadLabel(count: number | undefined): string {
if (count) return `${count} unread`;
return "Loading...";
}
unreadLabel(0); // "Loading...", halbuki oxunmamışların sayının 0 olduğunu bilirikTypeScript bu kodu qəbul edir. False budağında count yenə number | undefined-dir, çünki ədəd falsy ola bilər: tiplər düzgündür, məntiq səhvdir. Dəyərin 0, "" və ya NaN olması normaldırsa, nəyi nəzərdə tutduğunu açıq yaz:
if (count !== undefined) return `${count} unread`;Default dəyərlərdə də vəziyyət eynidir: count || 10 0-ı 10 ilə əvəz edir, count ?? 10 isə yalnız null və undefined-i.
Truthiness obyektlər və massivlər üçün düzgün yoxlamadır: onlar boş olanda da truthy-dir. user: User | null olanda if (user) etibarlı şəkildə "istifadəçi var" deməkdir. String və ədədlər üçün isə açıq müqayisəyə üstünlük ver.
typeof returns one of a fixed set of strings, and TypeScript narrows on each of them: "string", "number", "bigint", "boolean", "symbol", "undefined", "object" and "function".
function padLeft(padding: number | string, input: string): string {
if (typeof padding === "number") {
return " ".repeat(padding) + input;
}
return padding + input;
}The typeof null trap
In JavaScript, typeof null is "object", a historical accident that TypeScript models faithfully:
function printAll(items: string[] | null) {
if (typeof items === "object") {
for (const item of items) console.log(item);
// error: 'items' is possibly 'null'.
}
}The check narrowed items to string[] | null, not to string[]. Compare with null explicitly (items !== null), or use Array.isArray(items), which narrows to the array.
Truthiness
if (value) narrows too: in the true branch, null and undefined are gone. The falsy values in JavaScript are false, 0, -0, 0n, "", NaN, null and undefined (plus the legacy document.all), and the trap is that some of them are valid data:
function unreadLabel(count: number | undefined): string {
if (count) return `${count} unread`;
return "Loading...";
}
unreadLabel(0); // "Loading...", although we know there are 0 unreadTypeScript accepts this code. In the false branch count is still number | undefined, because a number can be falsy: the types are right, the logic is wrong. When a value can legitimately be 0, "" or NaN, say what you mean:
if (count !== undefined) return `${count} unread`;The same applies to defaults: count || 10 replaces 0 with 10, while count ?? 10 replaces only null and undefined.
Truthiness is the right check for objects and arrays, which are truthy even when empty: with user: User | null, if (user) safely means "the user exists". For strings and numbers, prefer explicit comparisons.
Bərabərlik, in və instanceof
Bərabərlik. ===, !==, == və ya != ilə müqayisə daraldır. Literal ilə müqayisə həmin literala qədər daraldır, theme === "system"-də olduğu kimi. null ilə müqayisə qeyri-sərt bərabərliyin (==, !=) idiomatik sayıldığı yeganə haldır: value != null həm null-u, həm də undefined-i istisna edir.
function displayName(name: string | null | undefined): string {
if (name != null) {
return name.trim(); // string
}
return "Anonymous";
}in operatoru obyektdə xassənin olub-olmadığını yoxlayır və union-ı həmin xassəyə malik üzvlərə qədər daraldır:
type Fish = { name: string; swim(): void };
type Bird = { name: string; fly(): void };
function move(animal: Fish | Bird) {
if ("swim" in animal) {
animal.swim(); // Fish
} else {
animal.fly(); // Bird
}
}Üzvlərdən biri xassəni optional elan edibsə, həmin üzv hər iki budaqda qalır, çünki xassə ola da bilər, olmaya da.
instanceof klassa qədər daraldır: value instanceof Date, error instanceof TypeError, event.target instanceof HTMLInputElement. O, klasslar icra zamanı mövcud olduğu üçün işləyir; mövcud olmayan interface və type alias-lar üçün isə işləmir.
function toDate(input: Date | string): Date {
return input instanceof Date ? input : new Date(input);
}
function onInput(event: Event) {
if (event.target instanceof HTMLInputElement) {
console.log(event.target.value); // event.target HTMLInputElement-dir
}
}İki xəbərdarlıq. instanceof prototip zəncirini yoxlayır, ona görə realm-lar arasında işləmir: iframe-də yaradılmış massiv əsas pəncərədə instanceof Array deyil; Array.isArray məhz buna görə var və TypeScript onunla da daraldır. Üstəlik, sadəcə düzgün formaya malik obyekt nümunə (instance) deyil: klass tipi gözlənilən yerə ötürülmüş adi obyekt tip yoxlamasından keçir, amma instanceof-dan keçmir.
Yoxlamanı seçmək
- Primitiv (
string,number,boolean,undefined):typeof. nullvə ya literal dəyər:===və ya!==; həmnull, həmundefinedüçün!= null.- Xassəsinə görə fərqlənən obyekt tipləri:
in, daha yaxşısı isə middle bölmələrində bəhs olunan ortaq literal sahə. - Klass nümunələri, daxili obyektlər, DOM elementləri:
instanceof. - Massivlər:
Array.isArray.
Bunların hər biri onsuz da yazacağın adi JavaScript-dir. TypeScript-in töhfəsi nəticəni ardınca gələn kod üçün yadda saxlamaqdır.
Equality. Comparing with ===, !==, == or != narrows. A comparison with a literal narrows to that literal, as with theme === "system". Loose equality with null is the one place where == is idiomatic: value != null excludes both null and undefined.
function displayName(name: string | null | undefined): string {
if (name != null) {
return name.trim(); // string
}
return "Anonymous";
}The in operator checks whether an object has a property, and narrows a union to the members that have it:
type Fish = { name: string; swim(): void };
type Bird = { name: string; fly(): void };
function move(animal: Fish | Bird) {
if ("swim" in animal) {
animal.swim(); // Fish
} else {
animal.fly(); // Bird
}
}If a member declares the property as optional, it stays on both sides, because the property may or may not be there.
instanceof narrows to a class: value instanceof Date, error instanceof TypeError, event.target instanceof HTMLInputElement. It works because classes exist at run time, and it doesn't work for interfaces or type aliases, which don't.
function toDate(input: Date | string): Date {
return input instanceof Date ? input : new Date(input);
}
function onInput(event: Event) {
if (event.target instanceof HTMLInputElement) {
console.log(event.target.value); // event.target is HTMLInputElement
}
}Two cautions. instanceof checks the prototype chain, so it fails across realms: an array created in an iframe is not instanceof Array in the main window, which is why Array.isArray exists, and TypeScript narrows on it too. And an object that merely has the right shape isn't an instance: a plain object passed where a class type is expected passes the type check but fails instanceof.
Choosing the check
- A primitive (
string,number,boolean,undefined):typeof. null, or a literal value:===or!==;!= nullfor bothnullandundefined.- Object types that differ by a property:
in, or better a shared literal field, covered in the middle sections. - Class instances, built-in objects, DOM elements:
instanceof. - Arrays:
Array.isArray.
Each of these is plain JavaScript that you would write anyway. TypeScript's contribution is to remember the result for the code that follows.
Control-flow analizi
TypeScript yalnız ən yaxın if-ə baxmır. O, funksiyadakı hər yolu (return-lər, throw-lar, mənimsətmələr, &&, ||, ?:, dövrlər) izləyir və hər nöqtədə hər dəyişənin tipini hesablayır. Handbook bunu control-flow analysis, yəni idarəetmə axınının analizi adlandırır.
Erkən return-lər özlərindən sonrakı hər şeyi daraldır, bu da əsas yolu düz saxlayır:
function sendWelcome(user: User | null, email: string | undefined) {
if (!user) return;
if (email === undefined) throw new Error("No email");
// burada user User, email isə string-dir
mailer.send(email, `Welcome, ${user.name}`);
}Mənimsətmələr elan olunmuş tip daxilində mənimsədilən tipə qədər daraldır:
let input: string | number = readInput();
input = String(input); // bundan sonra input string-dir
input.trim();Sabitlərdə saxlanan şərtlər də işləyir, bir şərtlə ki, yoxladıqları şey dəyişə bilməsin: const, readonly xassə və ya heç vaxt yenidən mənimsədilməyən parametr.
function shout(value: unknown) {
const isText = typeof value === "string";
if (isText) {
return value.toUpperCase(); // value string-dir
}
}&&, || və ?: sağ tərəflərini və budaqlarını daraldır: user !== null && user.name.length > 0 ifadəsində &&-dən sonra user User-dir.
Daraltma referansa aiddir
Hər daraltma bir referansa bağlıdır: dəyişənə, parametrə və ya order.customer.address kimi xassə yoluna. TypeScript həmin yolun daraltmasını ona və ya valideynlərindən birinə nəsə mənimsədilənə qədər saxlayır:
if (order.customer.address !== null) {
order.customer.address.city; // Address
order.customer = loadCustomer();
order.customer.address.city;
// xəta: 'order.customer.address' is possibly 'null'.
}order.customer-ə mənimsətmə onun altındakı hər şeyin daraltmasını sıfırlayır və bu, tamamilə düzgündür: yeni müştərinin ünvanı olmaya bilər.
Daraltmanı təbii hiss etdirən də budur: JavaScript-də onsuz da yazacağın yoxlamaları yazırsan, tiplər də ardınca gəlir. Analizin məhdudiyyətlərinin səbəbi də budur. TypeScript hər dəfə bir funksiya üzərində düşünür, çağırdığın funksiyaların və ötürdüyün callback-lərin içinə baxmır, ona görə yoxlama ilə istifadə arasında dəyərə nə baş verdiyini tam bilə bilmir. Növbəti bölmə bunun harada vacib olduğunu göstərir.
TypeScript doesn't only look at the nearest if. It follows every path through a function (returns, throws, assignments, &&, ||, ?:, loops) and computes the type of each variable at each point. The handbook calls this control-flow analysis.
Early returns narrow everything after them, which keeps the main path flat:
function sendWelcome(user: User | null, email: string | undefined) {
if (!user) return;
if (email === undefined) throw new Error("No email");
// here user is User and email is string
mailer.send(email, `Welcome, ${user.name}`);
}Assignments narrow to the assigned type, within the declared type:
let input: string | number = readInput();
input = String(input); // from here on, input is string
input.trim();Conditions stored in constants work as well, as long as what they test can't change: a const, a readonly property, or a parameter that is never assigned.
function shout(value: unknown) {
const isText = typeof value === "string";
if (isText) {
return value.toUpperCase(); // value is string
}
}&&, || and ?: narrow their right-hand side and branches: in user !== null && user.name.length > 0, user is a User after the &&.
Narrowing belongs to a reference
Each narrowing is tied to a reference: a variable, a parameter, or a property path such as order.customer.address. TypeScript keeps the narrowing of that path until something assigns to it or to one of its parents:
if (order.customer.address !== null) {
order.customer.address.city; // Address
order.customer = loadCustomer();
order.customer.address.city;
// error: 'order.customer.address' is possibly 'null'.
}The assignment to order.customer resets the narrowing of everything below it, which is exactly right: the new customer may have no address.
This is what makes narrowing feel natural: you write the checks you would write in JavaScript anyway, and the types follow. It is also why the analysis has limits. TypeScript reasons about one function at a time and doesn't look inside the functions you call or the callbacks you pass, so it can't know everything that happens to a value between the check and the use. The next section shows where that matters.
Daraltma harada itir
Üç vəziyyət yoxlama ilə sonrakı istifadə arasındakı əlaqəni qırır. Onlardan ikisində TypeScript sənin gördüyün daraltmanı unudur; üçüncüsündə isə artıq doğru olmayan daraltmanı saxlayır.
1. Callback-in içində oxunan xassə. Callback daha sonra, xassə artıq dəyişmiş ola biləndə işləyə bilər, ona görə TypeScript onun içində xassə yolunun daraltmasını atır:
function notifyAll(session: Session, ids: string[]) {
if (session.user !== null) {
ids.forEach((id) => {
send(id, session.user.name);
// xəta: 'session.user' is possibly 'null'.
});
}
}Yoxlamadan dərhal sonra dəyəri const-a köçür: const user = session.user;. const-a yenidən dəyər mənimsətmək olmur, ona görə onun daraltması hər callback-də qüvvədə qalır.
2. Yenidən mənimsədilən let dəyişəni və ya parametr. TypeScript 5.4-dən bəri let dəyişəninin və ya parametrin daraltması son mənimsətmədən sonra yaradılan closure-a keçir:
function schedule(label: string | undefined) {
if (label === undefined) label = "untitled";
setTimeout(() => console.log(label.toUpperCase())); // OK: bundan sonra mənimsətmə yoxdur
}label-ə setTimeout sətrindən sonra və ya hər hansı daxili funksiyanın içində yenidən dəyər mənimsət, closure yenə string | undefined görəcək. Həll eynidir: const surəti.
3. Yoxladığın şeyi dəyişən funksiya çağırışı. TypeScript funksiya çağırılanda daraltmanı sıfırlamır: hər çağırış hər yoxlamanı ləğv edə bilsəydi, daraltmanın faydası qalmazdı. Ona görə bu kod kompilyasiya olunur və çökür:
function farewell(session: Session): string {
if (session.user !== null) {
signOut(session); // session.user = null edir
return `Bye, ${session.user.name}`; // kompilyasiya olunur; icra zamanı TypeError
}
return "Nobody to sign out";
}Handbook bunu açıq deyir: TypeScript kompilyasiya zamanı təhlükəsiz olduğu bilinməyən bəzi əməliyyatlara icazə verir, yəni tip sistemi sound deyil. Burada da çarə çağırışdan əvvəl alınmış const surəti və ya ortaq state-i oxucudan xəbərsiz dəyişməyən koddur.
Nə etməməli
İlk iki halda cazibədar "düzəliş" non-null assertion-dır: session.user!.name. O, heç nəyi sübut etmədən xətanı yox edir, üçüncü halda isə bug-ı hətta gizlədərdi. TypeScript daraltmanı itirəndə soruş: yoxlama ilə istifadə arasında dəyəri nə dəyişə bilər? Cavab "heç nə"dirsə, onu const-a köçür; "nəsə"dirsə, düzəldilməli bug elə odur.
Three situations break the link between a check and a later use. In two of them TypeScript forgets a narrowing you can see; in the third, it keeps a narrowing that is no longer true.
1. A property read inside a callback. A callback may run later, when the property could have changed, so TypeScript drops the narrowing of a property path inside it:
function notifyAll(session: Session, ids: string[]) {
if (session.user !== null) {
ids.forEach((id) => {
send(id, session.user.name);
// error: 'session.user' is possibly 'null'.
});
}
}Copy the value into a const right after the check: const user = session.user;. A const can't be reassigned, so its narrowing holds in every callback.
2. A let variable or parameter that is assigned again. Since TypeScript 5.4, the narrowing of a let variable or a parameter carries into a closure created after its last assignment:
function schedule(label: string | undefined) {
if (label === undefined) label = "untitled";
setTimeout(() => console.log(label.toUpperCase())); // OK: no assignment after this
}Assign label again after the setTimeout line, or anywhere inside a nested function, and the closure sees string | undefined again. The fix is the same const copy.
3. A function call that changes what you checked. TypeScript doesn't reset narrowing when you call a function; if every call could undo every check, narrowing would be useless. So this compiles and crashes:
function farewell(session: Session): string {
if (session.user !== null) {
signOut(session); // sets session.user = null
return `Bye, ${session.user.name}`; // compiles; TypeError at run time
}
return "Nobody to sign out";
}The handbook says it plainly: TypeScript allows some operations that can't be known to be safe at compile time, so the type system is not sound. Here the remedy is again a const copy taken before the call, or code that doesn't change shared state behind the reader's back.
What not to do
The tempting fix for the first two cases is the non-null assertion: session.user!.name. It makes the error disappear without proving anything, and in the third case it would even hide the bug. When TypeScript loses a narrowing, ask what could change the value between the check and the use; if the answer is "nothing", copy it into a const, and if it is "something", that is the bug to fix.
unknown və tutulmuş xətalar
unknown any-nin tip baxımından təhlükəsiz qarşılığıdır. Hər ikisi istənilən dəyəri qəbul edir; any ilə sonra hər şeyi edə bilərsən, unknown ilə isə daraldana qədər heç nəyi. Buna görə forması hələ yoxlanmamış dəyərlər üçün düzgün tip unknown-dur: parse olunmuş JSON, postMessage datası, catch blokundakı dəyər.
unknown-u daraltmaq eyni yoxlamalarla, addım-addım aparılır:
function readName(data: unknown): string | undefined {
if (
typeof data === "object" &&
data !== null &&
"name" in data &&
typeof data.name === "string"
) {
return data.name; // string
}
return undefined;
}typeof data === "object" object | null saxlayır (yenə typeof null tələsi), data !== null object saxlayır, TypeScript 4.9-dan bəri isə "name" in data tipi unknown olan name xassəsi əlavə edir, sonuncu yoxlama da onu string-ə qədər daraldır. Bir-iki sahədən böyük hər şey üçün bu, uzun alınır və sxem kitabxanası daha yaxşı alətə çevrilir; ayrıca mövzudur.
Tutulmuş xətalar
JavaScript-də hər şeyi throw etmək olar: Error, string, ədəd, kitabxananın öz obyekti. strict rejimində (dəqiq desək, TypeScript 4.4-də əlavə olunan useUnknownInCatchVariables ilə) catch blokunun dəyişəni unknown-dur:
async function save(draft: Draft) {
try {
await saveDraft(draft);
} catch (error) {
console.error(error.message);
// xəta: 'error' is of type 'unknown'.
const message = error instanceof Error ? error.message : String(error);
showToast(`Could not save: ${message}`);
}
}Adi daraltma instanceof Error-dur, öz xəta klasslarını yoxlamaq (error instanceof HttpError) isə hər növü ayrıca emal etməyə imkan verir. Dəyişəni Error kimi annotasiya edə bilməzsən: TypeScript orada yalnız any və ya unknown qəbul edir ("Catch clause variable type annotation must be 'any' or 'unknown' if specified."), çünki nəyin throw olunduğuna heç nə zəmanət vermir. catch (error: any) bir blok üçün bu qaydadan imtina edir və yoxlanmamış xassə müraciətini geri qaytarır: string throw olunubsa, error.message sadəcə undefined olur, error.message.includes(...) isə xəta handler-inin özündə çökür.
any, yoxsa unknown?
any dəyərə etibar edir və heç nəyi yoxlamır; unknown heç nəyə etibar etmir və səni yoxlamağa məcbur edir. Kənardan daxil olan hər dəyər üçün unknown işlət, onu sərhəddə bir dəfə daralt və irəli dəqiq tiplər ötür. any yalnız yoxlamanın niyə mümkünsüz və ya mənasız olduğunu şərhdə izah edə bildiyin yerdə qəbul edilə bilər.
unknown is the type-safe counterpart of any. Both accept every value; with any you can then do anything, with unknown nothing until you narrow. That makes unknown the right type for values whose shape you haven't checked: parsed JSON, postMessage data, the value in a catch clause.
Narrowing unknown uses the same checks, step by step:
function readName(data: unknown): string | undefined {
if (
typeof data === "object" &&
data !== null &&
"name" in data &&
typeof data.name === "string"
) {
return data.name; // string
}
return undefined;
}typeof data === "object" leaves object | null (the typeof null trap again), data !== null leaves object, and since TypeScript 4.9, "name" in data adds a name property of type unknown, which the last check narrows to string. For anything bigger than a couple of fields this gets long, and a schema library becomes the better tool; is its own topic.
Caught errors
Anything can be thrown in JavaScript: an Error, a string, a number, a library's custom object. Under strict (precisely, useUnknownInCatchVariables, added in TypeScript 4.4), the variable of a catch clause is unknown:
async function save(draft: Draft) {
try {
await saveDraft(draft);
} catch (error) {
console.error(error.message);
// error: 'error' is of type 'unknown'.
const message = error instanceof Error ? error.message : String(error);
showToast(`Could not save: ${message}`);
}
}instanceof Error is the usual narrowing, and checking for your own error classes (error instanceof HttpError) lets you handle each kind separately. You can't annotate the variable as Error: TypeScript allows only any or unknown there ("Catch clause variable type annotation must be 'any' or 'unknown' if specified."), because nothing guarantees what was thrown. catch (error: any) opts one clause out and brings back unchecked access: error.message is simply undefined when a string was thrown, and error.message.includes(...) crashes inside your error handler.
any or unknown?
any trusts the value and checks nothing; unknown trusts nothing and makes you check. Use unknown for every value that enters from outside, narrow it once at the boundary, and pass precise types onward. An any is acceptable only where you can explain in a comment why checking is impossible or pointless.
Discriminated union-lar və tamlıq yoxlaması
State üçün geniş yayılmış forma bir neçə variantdır; hər variantda onun hansı variant olduğunu deyən literal sahə olur:
type RequestState =
| { status: "loading" }
| { status: "success"; data: string[] }
| { status: "error"; error: Error };Union-ın bütün üzvlərində literal tipli ortaq xassə olanda TypeScript onu kimi qəbul edir və həmin xassəni yoxlamaq bütöv obyekti daraldır:
function render(state: RequestState): string {
switch (state.status) {
case "loading":
return "Loading...";
case "success":
return state.data.join(", "); // burada state-də data var
case "error":
return state.error.message; // burada isə error
}
}switch-dən kənarda state.data xətadır ("Property 'data' does not exist on type 'RequestState'") və məqsəd də elə budur. Bunu optional sahələrdən ibarət tək obyektlə müqayisə et: { loading: boolean; data?: string[]; error?: Error }. O, "yüklənir, həm data, həm də xəta var" vəziyyətinə icazə verir və hər yerdə hər sahəni yoxlamağa məcbur edir. Union isə belə mümkünsüz vəziyyətləri yazmağı mümkünsüz edir.
Tamlıq yoxlaması
Yeni variant əlavə olunanda union üzərindəki hər switch onu emal etməlidir. Qoy onları kompilyator tapsın:
function assertNever(value: never): never {
throw new Error(`Unhandled value: ${JSON.stringify(value)}`);
}
function render(state: RequestState): string {
switch (state.status) {
case "loading":
return "Loading...";
case "success":
return state.data.join(", ");
case "error":
return state.error.message;
default:
return assertNever(state);
}
}default-da bütün variantlar artıq istisna olunub, ona görə state never-dir və çağırış kompilyasiya olunur. Union-a { status: "idle" } əlavə et, çağırış xətaya çevriləcək: "Argument of type '{ status: "idle"; }' is not assignable to parameter of type 'never'." Handbook bunun əvəzinə dəyişənə mənimsədir (const _exhaustiveCheck: never = state;), state satisfies never; da işləyir. default olmadan çatışmayan halı təkcə qaytarma tipi də tutur: "Function lacks ending return statement and return type does not include 'undefined'."
assertNever-dəki throw vacibdir, çünki tiplər silinir. Server union-da olmayan status göndərsə, kod icra zamanı default-a çatır və aydın xəta səssizcə səhv göstərilən ekrandan yaxşıdır.
A common shape for state is a set of variants, each with a literal field that says which variant it is:
type RequestState =
| { status: "loading" }
| { status: "success"; data: string[] }
| { status: "error"; error: Error };When every member has a common property with a literal type, TypeScript treats the union as a , and checking that property narrows the whole object:
function render(state: RequestState): string {
switch (state.status) {
case "loading":
return "Loading...";
case "success":
return state.data.join(", "); // state has data here
case "error":
return state.error.message; // and error here
}
}Outside the switch, state.data is an error ("Property 'data' does not exist on type 'RequestState'"), and that is the point. Compare it with one object of optional fields, { loading: boolean; data?: string[]; error?: Error }: it allows "loading, with data and an error" and forces a check of every field everywhere. The union makes such impossible states impossible to write.
Exhaustiveness checks
When a variant is added, every switch over the union has to handle it. Let the compiler find them:
function assertNever(value: never): never {
throw new Error(`Unhandled value: ${JSON.stringify(value)}`);
}
function render(state: RequestState): string {
switch (state.status) {
case "loading":
return "Loading...";
case "success":
return state.data.join(", ");
case "error":
return state.error.message;
default:
return assertNever(state);
}
}In default, every variant has been ruled out, so state is never and the call compiles. Add { status: "idle" } to the union and the call becomes an error: "Argument of type '{ status: "idle"; }' is not assignable to parameter of type 'never'." The handbook assigns to a variable instead (const _exhaustiveCheck: never = state;), and state satisfies never; works too. Without a default, the return type alone catches a missing case: "Function lacks ending return statement and return type does not include 'undefined'."
The throw in assertNever matters because types are erased. If the server sends a status the union doesn't list, the code reaches default at run time, and a clear error beats a silently wrong screen.
Type guard-lar, assertion funksiyaları və onlar necə yalan deyir
Yoxlama uzundursa və ya ada ehtiyacı varsa, onu type predicate qaytaran funksiyaya köçür:
interface User {
id: number;
name: string;
}
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
typeof value.id === "number" &&
"name" in value &&
typeof value.name === "string"
);
}
if (isUser(data)) {
data.name; // data User-dir
}
const users = rows.filter(isUser); // User[]value is User belə deməkdir: bu funksiya true qaytarırsa, value User-dir; false qaytarırsa, deyil. Çağırış daxili yoxlama kimi daraldır, filter isə predicate-dən massivi daraltmaq üçün istifadə edir.
Assertion funksiyası false qaytarmaq əvəzinə xəta ataraq daraldır:
function assertIsUser(value: unknown): asserts value is User {
if (!isUser(value)) throw new Error("Expected a user");
}
assertIsUser(data);
data.name; // scope-un qalan hissəsində data User-dirDigər forma, asserts condition, Node-un assert-i kimi işləyir: assert(root !== null, "No #root")-dan sonra root daralmış olur. Bir qayda çoxlarını təəccübləndirir: assertion funksiyası açıq tipi olan ad vasitəsilə çağırılmalıdır. Tip annotasiyası olmayan const-a mənimsədilmiş arrow funksiya və ya tipsiz obyekt literalının metodu belə xəta verir: "Assertions require every name in the call target to be declared with an explicit type annotation."
Guard bir iddiadır
TypeScript guard-ın gövdəsinin onun predicate-ini sübut edib-etmədiyini yoxlamır. Bu kod kompilyasiya olunur:
function isUser(value: unknown): value is User {
return typeof value === "object" && value !== null; // id və name unudulub
}İndi null olmayan hər obyekt User kimi keçir, çökmə isə çox uzaqda, hansısa kodun user.name.trim() çağırdığı yerdə baş verir. TypeScript 5.5-in buraxılış qeydləri bunu birbaşa deyir: açıq yazılmış type predicate-lər type assertion-dan daha təhlükəsiz deyil. Kompilyatorun yoxladığı yeganə şey predicate tipinin parametrin tipinə mənimsədilə bilməsidir.
Ona görə əl ilə yazılmış guard-a as kimi yanaş. Guard-ları az və kiçik saxla, tipin vəd etdiyi hər sahəni yoxla (və ya yoxlamanı da, tipi də bir sxemdən çıxar) və hər guard-ı uğursuz olmalı olan girişlə test et: sahəsi çatışmayan obyekt, səhv tipli sahə, null, string.
When a check is long or needs a name, move it into a function that returns a type predicate:
interface User {
id: number;
name: string;
}
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
typeof value.id === "number" &&
"name" in value &&
typeof value.name === "string"
);
}
if (isUser(data)) {
data.name; // data is User
}
const users = rows.filter(isUser); // User[]value is User means: if this returns true, value is a User; if it returns false, it is not. A call narrows like a built-in check, and filter uses the predicate to narrow the array.
An assertion function narrows by throwing instead of returning false:
function assertIsUser(value: unknown): asserts value is User {
if (!isUser(value)) throw new Error("Expected a user");
}
assertIsUser(data);
data.name; // data is User for the rest of the scopeThe other form, asserts condition, works like Node's assert: after assert(root !== null, "No #root"), root is narrowed. One rule surprises people: an assertion function has to be called through a name with an explicit type. A const arrow function without a type annotation on the const, or a method of an untyped object literal, fails with "Assertions require every name in the call target to be declared with an explicit type annotation."
A guard is a claim
TypeScript doesn't check that a guard's body proves its predicate. This compiles:
function isUser(value: unknown): value is User {
return typeof value === "object" && value !== null; // forgot id and name
}Every non-null object now passes as a User, and the crash happens far away, where some code calls user.name.trim(). The TypeScript 5.5 release notes say it directly: explicit type predicates are no safer than a type assertion. The only thing the compiler verifies is that the predicate's type is assignable to the parameter's type.
So treat a hand-written guard like an as. Keep guards few and small, check every field the type promises (or derive the check and the type from one schema), and test each guard with input that should fail: an object missing a field, a field of the wrong type, null, a string.
Çıxarılan type predicate-lər
TypeScript 5.5-dən əvvəl undefined-ləri filtrləmək massivin tipini dəyişmirdi:
const nicknames = users.map((u) => u.nickname); // (string | undefined)[]
const present = nicknames.filter((n) => n !== undefined);
// TypeScript 5.5 və sonra: string[]
// 5.5-dən əvvəl: (string | undefined)[]5.5-dən bəri TypeScript (n) => n !== undefined kimi funksiya üçün type predicate-i özü çıxarır, sanki (n): n is string => ... yazmısan. Buraxılış qeydləri şərtləri sadalayır:
- Funksiyanın açıq qaytarma tipi və ya type predicate annotasiyası yoxdur.
- Onun tək
returnifadəsi var və gizli (implicit) return yoxdur. - O, parametrini dəyişmir.
- O, parametrin daraldılmasına bağlı
booleanifadə qaytarır.
Beləliklə, const isNumber = (x: unknown) => typeof x === "number"; indi (x: unknown) => x is number tipinə malikdir və guard kimi işləyir.
true T deməkdir, false isə T deyil
Predicate hər iki istiqamətdə vəd verir: true dəyərin T olduğunu, false isə olmadığını bildirir. Ədədlər üzərində truthiness filtrinin predicate almamasının səbəbi budur:
const scores = [90, 0, undefined, 75];
const counted = scores.filter((s) => !!s);
// yenə (number | undefined)[]: false 0 demək də ola bilərTypeScript imtina edir, çünki funksiya number olan 0 üçün false qaytarır. Bu, həm də real bug-dır: sıfır bal nəticədən yox olur. Nəzərdə tutduğun yoxlamanı, s !== undefined-i yaz, onda sıfırı saxlayan number[] alırsan. Heç bir dəyəri falsy olmayan obyekt tiplərində truthiness yoxlaması predicate çıxarır: maybeUsers.filter((u) => !!u) User[] verir. filter(Boolean) isə yenə daraltmır; boolean qaytarmayan (x) => x də daraltmır.
Tip çıxarılmasının yan təsirləri
Daha dəqiq tiplər köhnə tiplərə güvənən kodu poza bilər. Buraxılış qeydlərindəki nümunə: [1, 2, 3, null, 5].filter((x) => x !== null) əvvəllər (number | null)[] idi, indi number[]-dir, ona görə sonrakı push(null) artıq kompilyasiya olunmur. Daha geniş tip istəyirsənsə, dəyişəni annotasiya et.
Açıq yazılmış predicate-lər əvvəlki kimi davranır. TypeScript onları özünün çıxaracağı predicate ilə müqayisə etmir, ona görə əl ilə yazılmış x is T yenə yalan deyə bilər; çıxarılan isə deyə bilməz, çünki o, kodun özündən alınır.
Before TypeScript 5.5, filtering out undefined didn't change the array's type:
const nicknames = users.map((u) => u.nickname); // (string | undefined)[]
const present = nicknames.filter((n) => n !== undefined);
// TypeScript 5.5 and later: string[]
// before 5.5: (string | undefined)[]Since 5.5, TypeScript infers a type predicate for a function like (n) => n !== undefined, as if you had written (n): n is string => .... The release notes list the conditions:
- The function has no explicit return type or type predicate annotation.
- It has a single
returnstatement and no implicit returns. - It doesn't mutate its parameter.
- It returns a
booleanexpression tied to a refinement on the parameter.
So const isNumber = (x: unknown) => typeof x === "number"; now has the type (x: unknown) => x is number and works as a guard.
True means T, false means not T
A predicate promises both directions: true means the value is T, false means it isn't. That is why a truthiness filter on numbers gets no predicate:
const scores = [90, 0, undefined, 75];
const counted = scores.filter((s) => !!s);
// still (number | undefined)[]: false could also mean 0TypeScript refuses because the function returns false for 0, which is a number. That is a real bug as well: the zero score disappears from the result. Write the check you mean, s !== undefined, and you get number[] with the zero kept. For object types, where no value is falsy, a truthiness check does infer a predicate: maybeUsers.filter((u) => !!u) gives User[]. filter(Boolean) still doesn't narrow, and neither does (x) => x, which doesn't return a boolean.
Side effects of the inference
The more precise types can break code that relied on the old ones. The release notes' example: [1, 2, 3, null, 5].filter((x) => x !== null) used to be (number | null)[] and is now number[], so a later push(null) no longer compiles. Annotate the variable when you want the wider type.
Explicit predicates behave exactly as before. TypeScript doesn't compare them with what it would infer, so a hand-written x is T can still lie; an inferred one can't, because it is derived from the code.
Müsahibə üçün məsləhətlər
30 saniyəlik cavab. "Narrowing TypeScript-in union-ı koddakı yoxlamalara əsasən dəqiqləşdirməsidir: typeof, truthiness, bərabərlik, in, instanceof və diskriminant xassələr. Control-flow analizi return-ləri və mənimsətmələri izləyir, amma callback-lərin içində xassələrin daraltmasını atır və funksiya çağırışlarından sonra onu sıfırlamır. unknown yoxlanmamış data və tutulmuş xətalar üçün təhlükəsiz tipdir. never yoxlaması olan discriminated union-lar emal olunmamış halları kompilyatora tapdırır. Proqramçının özünün yazdığı guard-lar və assertion funksiyaları daraltmanı genişləndirir, amma kompilyator onların gövdəsinə inanır, ona görə səhv guard as kimi yalan deyir."
Gözlənilən suallar
typeof items === "object"-dən sonraitemsniyə hələ dəstring[] | null-dur? Çünkitypeof null"object"-dir;nullilə müqayisə et və yaArray.isArrayişlət.if (count)-da nə səhvdir? O,0-ı (vəNaN-ı) olmayan dəyər kimi qəbul edir;undefinedilə müqayisə et.null-u yoxlamışam, TypeScript niyə buforEach-in içində şikayət edir? Callback-lərdə xassə daraltması atılır; dəyəriconst-a köçür.catchdəyişəninin tipi nədir?strictrejimindəunknown(useUnknownInCatchVariables);instanceof Errorilə daralt.- Union-ın hər halının emal olunduğuna necə əmin olursan? Discriminated union,
default-daneveryoxlaması və icra zamanı onsuz da gələ biləcək dəyərlər üçünthrow. x is T, yoxsaasserts x is T? Predicate boolean qaytarır və budağın içində daraldır; assertion xəta atır və scope-un qalanını daraldır.- TypeScript 5.5-də
filterüçün nə dəyişdi? Çıxarılan type predicate-lər:filter((x) => x !== undefined)indi massivi daraldır.
Bal itirdən səhvlər
- Type guard-ı "tipin yoxlanması" adlandırmaq. O, gövdəsi nəyi yoxlayırsa, onu yoxlayır; TypeScript bunun tiplə üst-üstə düşdüyünü heç vaxt yoxlamır.
- Daraltma xətasını yoxlama və ya
constsurəti əvəzinə!və yaasilə "düzəltmək". - Vərdiş üzündən ədəd və string-lərdə truthiness işlətmək.
- İcra zamanı budağı olmayan tam
switch-in serverdən gələn gözlənilməz dataya qarşı qoruduğuna inanmaq.
Senior səviyyəni göstərən məqamlar
State-i optional sahələrlə dolu obyektlər kimi yox, discriminated union-lar kimi modelləşdir. Əl ilə yazılmış guard-ları az, kiçik və test olunmuş saxla, ya da onları sxemlərdən yarat. Analizin harada sound olmadığını (funksiya çağırışları, guard-lar, assertion-lar, as, !) bil ki, "tip baxımından təhlükəsiz" proqram çökəndə əvvəlcə haraya baxacağını biləsən.
A 30-second answer. "Narrowing is how TypeScript refines a union based on checks in the code: typeof, truthiness, equality, in, instanceof and discriminant properties. Control-flow analysis follows returns and assignments, but it drops the narrowing of properties inside callbacks and doesn't reset it after function calls. unknown is the safe type for unchecked data and caught errors. Discriminated unions with a never check make the compiler find unhandled cases. User-defined guards and assertion functions extend narrowing, but the compiler trusts their bodies, so a wrong guard lies like an as."
Questions you are likely to get
- Why is
itemsstillstring[] | nullaftertypeof items === "object"? Becausetypeof nullis"object"; compare withnullor useArray.isArray. - What's wrong with
if (count)? It treats0(andNaN) like a missing value; compare withundefined. - Why does TypeScript complain inside this
forEachalthough I checked fornull? Property narrowing is dropped in callbacks; copy the value into aconst. - What type does a
catchvariable have?unknownunderstrict(useUnknownInCatchVariables); narrow withinstanceof Error. - How do you make sure every case of a union is handled? A discriminated union, a
nevercheck indefault, and athrowfor values that arrive at run time anyway. x is Torasserts x is T? A predicate returns a boolean and narrows inside the branch; an assertion throws and narrows the rest of the scope.- What changed for
filterin TypeScript 5.5? Inferred type predicates:filter((x) => x !== undefined)now narrows the array.
Mistakes that cost points
- Calling a type guard a check "of the type". It checks whatever its body checks; TypeScript never verifies that this matches the type.
- Fixing a narrowing error with
!orasinstead of a check or aconstcopy. - Using truthiness on numbers and strings out of habit.
- Believing an exhaustive
switchprotects against unexpected data from a server without a runtime branch.
Senior signal
Model state as discriminated unions instead of objects full of optional fields. Keep hand-written guards few, small and tested, or generate them from schemas. Know where the analysis is unsound (function calls, guards, assertions, as, !), so that when a "type-safe" program crashes, you know where to look first.
Narrowing və type guard-ları review edərkən nəyi yoxlamalı
Yazmadığın TypeScript 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. Daraltma səhvləri təmiz kompilyasiya olunur. Yoxlamalar düzgün görünür, bug isə yalnız heç kimin sınamadığı dəyərdə üzə çıxır: sıfırda, boş string-də, serverin sonradan əlavə etdiyi statusda.
- Truthiness yoxlamaları ədədlər və ya string-lər üzərində aparılırmı?
if (count),if (!title)vəvalue || fallback0-ı, boş string-i vəNaN-ı olmayan dəyər kimi qəbul edir. Onları diff-də tap və sıfırın və ya boş string-in orada düzgün dəyər olub-olmadığını soruş; əgər belədirsə,undefinedvə yanullilə müqayisə et, ya da??işlət. typeof x === "object"yoxlamasından sonranullyoxlaması varmı?typeof null"object"-dir, ona görə təkcə bu yoxlamanull-u buraxır. Yanındax !== nullaxtar və ya tipinnullehtiva edə bilmədiyinə əmin ol.- Union üzərindəki hər
switchvə yaifzənciri tamlıq yoxlaması ilə bitirmi? Dəyərineverparametrə ötürən və xəta atandefaultaxtar. Öz kompüterində union-a üzv əlavə et vətsc-nin dəyişməli olan hər yeri göstərdiyinə əmin ol. - Əl ilə yazılmış hər type guard predicate-inin vəd etdiyi hər şeyi yoxlayırmı?
x is Userfunksiyasının gövdəsiniUsertipi ilə sahə-sahə müqayisə et: bir sahəni yoxlayan guard hamısına zəmanət verir. Onu sahəsi çatışmayan obyektlə çağır vəfalseqaytardığına əmin ol. - Daraltma xətası
!və yaasilə susdurulubmu? TypeScript-in qəbul etmədiyi yoxlamadan sonra yazılmışsession.user!.namevə yadata as Useradətən real halı gizlədir: sonra işləyən callback-i, dəyəri dəyişən funksiya çağırışını, heç vaxt yoxlanmamış datanı. Bunun əvəzinə yoxlamadan sonraconstsurəti və ya real guard istə. - Tutulmuş xətalar daraltmadan istifadə olunurmu?
catch (error: any)və yaerror as Errorilə handler string və ya adi obyekt ola biləcək şeydənerror.messageoxuyur. Xətanın xassələrindən istifadə etməzdən əvvəl kodunerror instanceof Error-u (və ya öz xəta klasslarını) yoxladığına əmin ol.
Use this list when you review TypeScript you did not write: a teammate's pull request, a library's example, an AI assistant's suggestion. Narrowing mistakes compile cleanly. The checks look right, and the bug appears only for the value nobody tried: a zero, an empty string, a status the server added later.
- Do truthiness checks run on numbers or strings?
if (count),if (!title)andvalue || fallbacktreat0,""andNaNlike missing values. Find them in the diff and ask whether zero or an empty string is valid there; if it is, compare withundefinedornull, or use??. - Is a
typeof x === "object"check followed by anullcheck?typeof nullis"object", so the check alone letsnullthrough. Look forx !== nullnext to it, or confirm that the type can't containnull. - Does every
switchorifchain over a union end in an exhaustiveness check? Look for adefaultthat passes the value to aneverparameter and throws. Add a member to the union locally and confirm thattscreports every place that has to change. - Does each hand-written type guard check everything its predicate promises? Compare the body of an
x is Userfunction with theUsertype field by field: a guard that checks one field certifies all of them. Call it with an object that lacks a field and confirm it returnsfalse. - Is a narrowing error silenced with
!oras?session.user!.nameordata as Userwhere TypeScript didn't accept a check usually hides a real case: a callback that runs later, a function call that changed the value, data that was never validated. Ask for aconstcopy after the check or a real guard instead. - Are caught errors used without narrowing? With
catch (error: any)orerror as Error, the handler readserror.messagefrom something that may be a string or a plain object. Check that the code testserror instanceof Error(or its own error classes) before using the error's properties.