Structural typing and type erasure
What TypeScript is and what it is not: a type checker whose types are erased before the code runs, structural compatibility and excess property checks, interface vs type, any, unknown and never, the strict flags that matter, erasable syntax and branded types.
Reading level
Shows sections up to the selected level.
Before you start
No prerequisites.
This topic starts at Junior level.
What TypeScript is
TypeScript tip sintaksisi əlavə olunmuş JavaScript-dir. JavaScript barədə bildiyin hər şey qüvvədə qalır: eyni dəyərlər, eyni operatorlar, eyni runtime. TypeScript isə bu dəyərləri təsvir etmək üçün sintaksis və həmin təsvirləri oxuyan alət əlavə edir.
function greet(user: { name: string }): string {
return `Hello, ${user.name}`;
}
greet({ name: "Ada" });
greet("Ada"); // xəta: Argument of type 'string' is not assignable to parameter of type '{ name: string; }'.TypeScript iki ayrı iş görür:
- Tip yoxlaması. Tip yoxlayıcısı (type checker) kodu oxuyur və dəyərin öz tipinə uyğun gəlmədiyi yerləri göstərir. Redaktorun da sən yazdıqca eyni yoxlayıcını işə salır; qırmızı alt xətlər oradan gəlir.
- JavaScript yaratmaq. Brauzer və Node JavaScript icra edir, ona görə tip sintaksisi aradan götürülməlidir. Tiplər silinir, geriyə adi JavaScript qalır:
function greet(user) {
return `Hello, ${user.name}`;
}Bu silinməyə deyilir. TypeScript handbook-u bunu qayda kimi yazır: tip annotasiyaları proqramın icra zamanı davranışını heç vaxt dəyişmir.
Yoxlamaq və silmək ayrı alətlərin işidir
TypeScript kompilyatoru tsc hər iki işi görür. Bir çox alət isə yalnız ikincisini görür: Node .ts faylındakı tipləri boşluqlarla əvəz edib faylı birbaşa işə salır, esbuild və Sucrase kimi transpilyatorlar isə TypeScript-i fayl-fayl JavaScript-ə çevirir. Onlar sürətlidir, çünki tipləri heç vaxt yoxlamırlar.
npx tsc --noEmit # layihənin tiplərini yoxla, heç bir fayl yazma
node server.ts # tipləri sil və işə sal; heç nə yoxlanmırnoEmitOnError qoşulmayıbsa, tsc özü də tip xətası tapanda JavaScript-i yenə yazır. Handbook bunun səbəbini izah edir: JavaScript-dən köçürülən layihə sən onun tiplərini düzəldənə qədər işləməyə davam etməlidir.
Praktik nəticə: tip xətası özü heç nəyi dayandırmır. Tipləri yalnız silən alət kodu hər halda işə salır. Bəzi framework-lər build zamanı yoxlayıcını da işə salır; belə deyilsə, layihəyə ayrıca tip yoxlaması addımı lazımdır, adətən CI-da işləyən tsc --noEmit skripti. Redaktordakı qırmızı alt xətt isə formallıq yox, bug barədə xəbərdir.
TypeScript is JavaScript with type syntax added. Everything you know about JavaScript still holds: the same values, the same operators, the same runtime. TypeScript adds a way to describe those values, and a tool that reads the descriptions.
function greet(user: { name: string }): string {
return `Hello, ${user.name}`;
}
greet({ name: "Ada" });
greet("Ada"); // error: Argument of type 'string' is not assignable to parameter of type '{ name: string; }'.TypeScript does two separate jobs:
- Type checking. The type checker reads your code and reports the places where a value doesn't match its type. Your editor runs the same checker while you type; that is where the red underlines come from.
- Producing JavaScript. Browsers and Node run JavaScript, so the type syntax has to go. The types are removed, and what remains is ordinary JavaScript:
function greet(user) {
return `Hello, ${user.name}`;
}That removal is . The TypeScript handbook states it as a rule: type annotations never change the runtime behavior of your program.
Checking and stripping are different tools
tsc, the TypeScript compiler, does both jobs. Many tools do only the second: Node runs a .ts file directly by replacing the types with whitespace, and transpilers such as esbuild and Sucrase convert TypeScript to JavaScript one file at a time. They are fast because they never check types.
npx tsc --noEmit # type-check the project, write no files
node server.ts # strip the types and run; nothing is checkedEven tsc writes the JavaScript when it finds type errors, unless you turn on noEmitOnError. The handbook explains why: a project being migrated from JavaScript should keep running while you fix its types.
The practical consequence: a type error stops nothing by itself. A tool that only strips types runs the code anyway. Some frameworks run the checker as part of their build; otherwise the project needs its own type-check step, usually a tsc --noEmit script that runs in CI. And a red underline in the editor is a bug report, not a formality.
Types describe shapes
Java və ya C#-da klass tipə yalnız elanında bu açıq yazılıbsa uyğun gəlir (class Dog implements Pet). Bu, nominal tipləşdirmədir: adlar və elanlar həlledicidir. TypeScript başqa cür işləyir. Dəyərdə tipin tələb etdiyi bütün üzvlər uyğun tiplərlə varsa, dəyər həmin tipə uyğun gəlir; onun haradan gəldiyi və necə adlandığı fərq etmir. Buna deyilir və bu, JavaScript-in real yazılış tərzinə uyğundur: adi obyektlər ötürülür və içindəkilərə görə istifadə olunur.
interface Point {
x: number;
y: number;
}
function length(p: Point): number {
return Math.hypot(p.x, p.y);
}
const reading = { x: 3, y: 4, label: "sensor" };
length(reading); // OK: x və y var
class Vector {
x = 1;
y = 2;
}
length(new Vector()); // OK: "implements Point" lazım deyilreading heç vaxt Point kimi elan olunmayıb və onda artıq label də var. Yenə də uyğun gəlir, çünki Point-in istədiyi hər şey yerindədir.
Assignability
TypeScript bunu bir sözlə ifadə edir: assignable, yəni mənimsədilə bilən. B gözlənilən hər yerdə A tipli dəyəri işlətmək olursa, A tipi B-yə mənimsədilə biləndir. Artıq xassələr problem deyil. Çatışmayan və ya səhv tipli xassə isə xətadır:
interface User {
name: string;
age: number;
}
const draft = { name: "Ada" };
const user: User = draft;
// xəta: Property 'age' is missing in type '{ name: string; }'
// but required in type 'User'.Qayda obyektlərlə məhdudlaşmır. Çağıranın ötürdüyündən az parametr qəbul edən callback də mənimsədilə biləndir: forEach üç arqument ötürsə də, items.forEach((item) => ...) məhz buna görə tip yoxlamasından keçir.
Klassdakı implements TypeScript-dən klassı yazdığın anda interface-ə qarşı yoxlamağı xahiş edir. O, başqa kodun asılı olduğu bir əlaqə yaratmır: düzgün formalı istənilən obyekt yenə də həmin interface-ə uyğun gəlir.
Deməli, eyni formalı iki tip, adlarından asılı olmayaraq, yoxlayıcı üçün eyni tipdir. Adətən sənə lazım olan da budur. Lazım olmayanda, məsələn, hər ikisi string olan istifadəçi id-si ilə sifariş id-si qarışmamalı olanda, tipləri nominal kimi davranmağa məcbur etməyin yolları var; mövzunun senior hissəsi onlardan bəhs edir.
In Java or C#, a class fits a type only if its declaration says so (class Dog implements Pet). That is nominal typing: names and declarations decide. TypeScript works differently. A value fits a type when it has the members the type requires, with compatible types; where the value came from and what it is called don't matter. This is , and it matches how JavaScript is written: plain objects passed around and used for what they contain.
interface Point {
x: number;
y: number;
}
function length(p: Point): number {
return Math.hypot(p.x, p.y);
}
const reading = { x: 3, y: 4, label: "sensor" };
length(reading); // OK: it has x and y
class Vector {
x = 1;
y = 2;
}
length(new Vector()); // OK: no "implements Point" neededreading was never declared as a Point, and it has an extra label. It still fits, because everything Point asks for is there.
Assignability
TypeScript describes this with one word: assignable. A type A is assignable to B when a value of A can be used wherever a B is expected. Extra properties are fine. A missing property, or one of the wrong type, is an error:
interface User {
name: string;
age: number;
}
const draft = { name: "Ada" };
const user: User = draft;
// error: Property 'age' is missing in type '{ name: string; }'
// but required in type 'User'.The rule goes beyond objects. A callback that takes fewer parameters than the caller passes is assignable too, which is why items.forEach((item) => ...) type-checks although forEach passes three arguments.
implements on a class asks TypeScript to check the class against an interface while you write it. It doesn't create a link that other code depends on: any object of the right shape still fits the interface.
So two types with the same shape are the same type for the checker, whatever their names. Usually that is what you want. When it isn't, for example a user id and an order id that are both strings, there are ways to make types behave nominally; the senior part of this topic covers them.
Excess property checks
Artıq xassələrə icazə var, bir yerdən başqa. Obyekt literalını birbaşa tip gözlənilən yerdə yazanda TypeScript onda tipin bilmədiyi xassə olub-olmadığını yoxlayır:
type DrawOptions = { color?: string; width?: number };
function draw(options: DrawOptions) {
// ...
}
draw({ colour: "red", width: 100 });
// xəta: Object literal may only specify known properties, but 'colour'
// does not exist in type 'DrawOptions'. Did you mean to write 'color'?Bu, artıq xassə yoxlamasıdır (excess property check) və yalnız təzə (fresh) obyekt literallarına aiddir, yəni elə həmin yerdə — mənimsətmədə, arqumentdə və ya return-də — yazılmış obyektlərə. Belə obyektə başqa heç bir kod müraciət edə bilmir, ona görə tipin tanımadığı xassə demək olar ki, həmişə hərf səhvidir. Handbook qeyd edir ki, artıq xassə xətalarının çoxu real bug-lardır.
Əvvəlcə dəyişənə yazılmış eyni obyekt artıq təzə deyil və yoxlamadan keçir:
const options = { colour: "red", width: 100 };
draw(options); // xəta yoxdur: "colour" səssizcə nəzərə alınmıroptions adi struktur qaydasına görə DrawOptions-a mənimsədilə biləndir: onda width var, optional color isə olmaya da bilər. Hərf səhvi yerində qalır və xətt standart rənglə çəkilir. Obyekti literalın içinə spread etmək ({ ...base }) də həmin obyektin artıq xassələrini yoxlamır.
Tiplər xassələri silmir
Eyni qayda çoxlarını təəccübləndirən bir sızmanı da izah edir. Daha dar tip xassələri proqramdan yox, yalnız yoxlayıcıdan gizlədir:
interface User {
id: number;
name: string;
passwordHash: string;
}
type PublicUser = { id: number; name: string };
function toPublic(user: User): PublicUser {
return user; // OK: User PublicUser-ə mənimsədilə biləndir
}
const user: User = { id: 7, name: "Ada", passwordHash: "x9f2" };
const body = JSON.stringify(toPublic(user)); // passwordHash yenə də içindədirQaytarma tipi PublicUser deyir, amma dəyər bütöv user obyektidir və JSON.stringify onda olan hər şeyi serializasiya edir. Kənara yalnız bəzi sahələr çıxmalıdırsa — API cavabında, log sətrində və ya client-ə gedən mesajda — məhz həmin sahələrlə yeni obyekt qur: return { id: user.id, name: user.name };.
Artıq xassə xətasını as assertion ilə susdurma. Hərf səhvini düzəlt, ya da xassə həqiqətən oraya aiddirsə, tipi düzəlt.
Extra properties are allowed, except in one place. When you write an object literal directly where a type is expected, TypeScript checks it for properties the type doesn't have:
type DrawOptions = { color?: string; width?: number };
function draw(options: DrawOptions) {
// ...
}
draw({ colour: "red", width: 100 });
// error: Object literal may only specify known properties, but 'colour'
// does not exist in type 'DrawOptions'. Did you mean to write 'color'?This is the excess property check, and it applies only to fresh object literals: objects written right there, in an assignment, an argument or a return. Nothing else can refer to such an object, so a property the type doesn't know is almost always a typo. The handbook notes that most excess property errors are real bugs.
The same object stored in a variable first is not fresh, and passes:
const options = { colour: "red", width: 100 };
draw(options); // no error: "colour" is silently ignoredoptions is assignable to DrawOptions under the normal structural rule: it has width, and the optional color may be missing. The typo survives, and the line is drawn in the default color. Spreading an object into a literal ({ ...base }) doesn't check the spread object's extra properties either.
Types don't remove properties
The same rule explains a leak that surprises people. A narrower type hides properties from the checker, not from the program:
interface User {
id: number;
name: string;
passwordHash: string;
}
type PublicUser = { id: number; name: string };
function toPublic(user: User): PublicUser {
return user; // OK: User is assignable to PublicUser
}
const user: User = { id: 7, name: "Ada", passwordHash: "x9f2" };
const body = JSON.stringify(toPublic(user)); // still contains passwordHashThe return type says PublicUser, but the value is the whole user object, and JSON.stringify serialises everything it has. When only some fields may leave, in an API response, a log line or a message to the client, build a new object with exactly those fields: return { id: user.id, name: user.name };.
Don't silence an excess property error with an as assertion. Fix the typo, or fix the type if the property really belongs there.
Types don't exist at run time
Tiplər silindiyi üçün işləyən proqram onları görə bilmir. Bunun üç nəticəsi TypeScript-ə yeni başlayanları tez-tez çaşdırır.
Dəyəri interface-ə qarşı yoxlamaq olmur. Interface-in və ya type alias-ın JavaScript-də qarşılığı yoxdur, yəni müqayisə ediləcək heç nə yoxdur:
interface Admin {
role: "admin";
permissions: string[];
}
function isAdmin(value: unknown) {
return value instanceof Admin;
// xəta: 'Admin' only refers to a type, but is being used as a value here.
}instanceof klasslarla işləyir, çünki klass JavaScript dəyəridir, konstruktor funksiyadır, instanceof isə icra zamanı obyektin prototip zəncirini yoxlayır. Interface üçün yoxlamanı JavaScript əməliyyatları (typeof, in, Array.isArray, müqayisələr) ilə özün yazırsan, TypeScript də həmin yoxlamalardan nəticə çıxarır. Bu, narrowing-dir, növbəti mövzu.
Annotasiya yoxlama deyil, vəddir. Proqrama kənardan gələn datanı heç nə yoxlamır:
interface Product {
title: string;
price: number;
}
const product: Product = JSON.parse('{"title":"Kettle","price":"25"}');
const total = product.price + 5; // "255": icra zamanı price string-dirJSON.parse any qaytarır, ona görə TypeScript annotasiyanı sual vermədən qəbul edir. await response.json() üçün də eyni şey doğrudur; localStorage-dan, URL parametrlərindən və ya form sahələrindən oxunan hər şey isə, sonra ona hansı tipi aid etməyindən asılı olmayaraq, adi string kimi başlayır. Kompilyator sənin yazdığına inanır, data isə buna əhəmiyyət vermir. Kənardan gələn dəyərlər icra zamanı yoxlanmalıdır, əl ilə və ya sxem kitabxanası ilə; ayrıca mövzudur.
Tipin üzvlərini siyahı kimi almaq olmur. Proqram işləyərkən Product-ın hansı xassələri olduğunu soruşmağın yolu yoxdur, məsələn, form və ya cədvəl başlığı qurmaq üçün. Əks istiqamətdə get: icra zamanı mövcud olan dəyərdən başla və tipi ondan çıxar.
const productFields = ["title", "price"] as const;
type ProductField = (typeof productFields)[number]; // "title" | "price"Massiv yaradılan JavaScript kodunda mövcuddur, tip də onun ardınca gəlir, ona görə ikisi bir-birindən ayrı düşə bilməz.
Eyni qayda yalnız tiplərə aid hər şeyə şamil olunur: type, interface, generic parametrləri, as assertion-ları və ! operatoru yoxa çıxır. Kodun bir parçası yalnız TypeScript-ə nəsə deyirsə, proqram işləyəndə heç nə etmir.
Because types are erased, the running program can't see them. Three consequences catch people who are new to TypeScript.
You can't test a value against an interface. An interface or a type alias has no JavaScript counterpart, so there is nothing to compare with:
interface Admin {
role: "admin";
permissions: string[];
}
function isAdmin(value: unknown) {
return value instanceof Admin;
// error: 'Admin' only refers to a type, but is being used as a value here.
}instanceof works with classes because a class is a JavaScript value, a constructor function, and instanceof checks the object's prototype chain at run time. For an interface you write the check yourself with JavaScript operations (typeof, in, Array.isArray, comparisons), and TypeScript learns from those checks. That is narrowing, the next topic.
An annotation is a promise, not a check. Nothing verifies data that comes from outside the program:
interface Product {
title: string;
price: number;
}
const product: Product = JSON.parse('{"title":"Kettle","price":"25"}');
const total = product.price + 5; // "255": price is a string at run timeJSON.parse returns any, so TypeScript accepts the annotation without question. The same is true of await response.json(), and anything read from localStorage, URL parameters or form fields starts as a plain string, whatever type you later claim for it. The compiler trusts what you write; the data doesn't care. Values from outside must be checked at run time, by hand or with a schema library; has its own topic.
You can't list a type's members. There is no way to ask, while the program runs, which properties Product has, for example to build a form or a table header. Go the other way: start from a value that exists at run time and derive the type from it.
const productFields = ["title", "price"] as const;
type ProductField = (typeof productFields)[number]; // "title" | "price"The array exists in the JavaScript output and the type follows it, so the two can't drift apart.
The same holds for everything type-only: type, interface, generic parameters, as assertions and the ! operator all disappear. If a piece of code only tells TypeScript something, it does nothing when the program runs.
interface or type alias?
Hər iki elan obyektin formasına ad verir və obyektlərin çoxu üçün istənilənini işlədə bilərsən:
interface User {
id: string;
name: string;
}
type UserRecord = {
id: string;
name: string;
};Struktur tipləşdirmə sayəsində birinə uyğun gələn dəyər digərinə də uyğun gəlir. Fərqlər onların başqa nələr bacardığındadır.
Type alias istənilən tipə ad verə bilər. Union-lar, literal tiplər, tuple-lar, funksiya tipləri və başqa tiplərdən hesablanan tiplər (mapped və conditional tiplər) üçün type lazımdır:
type Status = "idle" | "loading" | "done";
type Pair = [string, number];
type OnSelect = (id: string) => void;Interface-lər birləşir. Eyni scope-da eyni adlı iki interface elanı hər ikisinin üzvlərindən ibarət tək interface-ə çevrilir. Buna declaration merging (elanların birləşməsi) deyilir və sənə aid olmayan tiplərə, məsələn, brauzerin qlobal obyektinə və ya kitabxananın interface-inə üzv əlavə etməyin yolu məhz budur:
// globals.d.ts
interface Window {
analytics?: { track(event: string): void };
}
// tətbiqin istənilən yerində
window.analytics?.track("page_view"); // tip yoxlamasından keçirEyni adlı ikinci type isə xətadır: "Duplicate identifier". Birləşmənin digər üzü odur ki, o, səssiz baş verir: eyni qlobal scope-dakı bir-biri ilə əlaqəsiz iki interface Config elanı heç bir xəbərdarlıq olmadan birləşir.
extends konflikti göstərir, & gizlədir. Miras aldığı xassəni uyğunsuz tiplə yenidən elan edən interface elan yerində xəta verir. Eyni konfliktli intersection isə kompilyasiya olunur və xassənin tipi never olur:
interface Base {
id: string;
}
interface Broken extends Base {
id: number; // xəta: Interface 'Broken' incorrectly extends interface 'Base'.
}
type Mixed = Base & { id: number }; // xəta yoxdur, amma Mixed["id"] never-dirHandbook da eyni şeyi deyir: genişləndirmə ilə kəsişmə arasındakı əsas fərq konfliktlərin necə həll olunmasıdır.
Hansını seçməli
Handbook-un sadə qaydası belədir: "type-ın imkanları lazım olana qədər interface işlət". Bir çox komanda isə əksini edir: hər yerdə type yazır, interface-i isə birləşmə üçün saxlayır. Hər ikisi məntiqlidir. Vacib olan kod bazasının bir konvensiyaya əməl etməsidir, yaxşı olar ki, lint qaydası ilə; belə ki, oxucu seçimin nəsə demək olub-olmadığı barədə düşünməsin.
Both declarations name an object shape, and for most objects you can use either:
interface User {
id: string;
name: string;
}
type UserRecord = {
id: string;
name: string;
};Thanks to structural typing, a value that fits one fits the other. The differences are in what else each can do.
A type alias can name any type. Unions, literal types, tuples, function types and types computed from other types (mapped and conditional types) need type:
type Status = "idle" | "loading" | "done";
type Pair = [string, number];
type OnSelect = (id: string) => void;Interfaces merge. Two interface declarations with the same name in the same scope become one interface with the members of both. This is declaration merging, and it is how you add members to types you don't own, such as a browser global or a library's interface:
// globals.d.ts
interface Window {
analytics?: { track(event: string): void };
}
// anywhere in the app
window.analytics?.track("page_view"); // type-checksA second type with the same name is an error instead: "Duplicate identifier". The other side of merging is that it happens silently: two unrelated interface Config declarations in the same global scope combine without a warning.
extends reports conflicts; & hides them. An interface that redeclares an inherited property with an incompatible type fails at the declaration. An intersection with the same conflict compiles, and the property's type becomes never:
interface Base {
id: string;
}
interface Broken extends Base {
id: number; // error: Interface 'Broken' incorrectly extends interface 'Base'.
}
type Mixed = Base & { id: number }; // no error, but Mixed["id"] is neverThe handbook makes the same point: the main difference between extending and intersecting is how conflicts are handled.
Which one to use
The handbook's heuristic is "use interface until you need to use features from type". Many teams do the opposite and use type everywhere, keeping interface for merging. Both are reasonable. What matters is that the codebase follows one convention, ideally enforced by a lint rule, so that a reader doesn't wonder whether the choice means something.
any, unknown and never
TypeScript-in elə ilk həftəsindən üç xüsusi tip qarşına çıxır. Narrowing mövzusu unknown-a daha dərindən baxır; burada isə hər birinin nə demək olduğunu görəcəksən.
any yoxlayıcını söndürür. any dəyər üzərində hər əməliyyata icazə var, any istənilən tipə mənimsədilə bilir, ondan oxuduğun hər şey də yenə any olur:
const data: any = JSON.parse('"hello"');
data.toFixed(2); // kompilyasiya olunur; icra zamanı TypeError atır
const n: number = data; // kompilyasiya olunur; n-də string varany yayılır: JSON.parse-dan və ya response.json()-dan gələn bir any funksiya çağırışları və obyekt xassələri vasitəsilə tam tipli görünən koda axır. TypeScript tipi çıxara bilmədiyi yerdə, məsələn, annotasiyasız parametrdə də any-yə keçir; noImplicitAny bunu xətaya çevirir: "Parameter 'a' implicitly has an 'any' type."
unknown hər şeyi qəbul edir, heç nəyə icazə vermir. any kimi, hər dəyər unknown-a mənimsədilə bilir. any-dən fərqli olaraq, dəyərin nə olduğunu yoxlamayınca ondan istifadə edə bilməzsən:
const input: unknown = JSON.parse('"hello"');
input.toUpperCase();
// xəta: 'input' is of type 'unknown'.
if (typeof input === "string") {
input.toUpperCase(); // OK: yoxlama onun string olduğunu sübut etdi
}Buna görə unknown hələ yoxlamadığın hər şey üçün dürüst tipdir: parse olunmuş JSON, başqa pəncərədən gələn mesaj, tutulmuş xəta.
never-in heç bir dəyəri yoxdur. O, normal qayıtmayan, həmişə xəta atan funksiyanın qaytarma tipidir və bütün variantlar istisna olunandan sonra TypeScript-in dəyərə verdiyi tipdir:
function fail(message: string): never {
throw new Error(message);
}never istənilən tipə mənimsədilə bilir, never-in özündən başqa heç bir tip isə ona mənimsədilə bilmir. Tamlıq yoxlamaları (exhaustiveness check) məhz ikinci xassəyə əsaslanır: dəyəri never-ə mənimsət, kompilyator unutduğun hər halı göstərəcək.
accepts any value? usable without a check?
any yes yes (nothing is checked)
unknown yes no
never no (it has no values) -Yaxşı işləyən qayda: datanın daxil olduğu kənarlarda unknown işlət, diff-də gördüyün hər any-yə isə kiminsə izah etməli olduğu qərar kimi bax.
Three special types appear from the first week of TypeScript. The narrowing topic goes deeper into unknown; here is what each one means.
any switches the checker off. Every operation on an any value is allowed, any is assignable to every type, and whatever you read from it is any again:
const data: any = JSON.parse('"hello"');
data.toFixed(2); // compiles; throws a TypeError at run time
const n: number = data; // compiles; n holds a stringany spreads: one any from JSON.parse or response.json() flows through function calls and object properties into code that looks fully typed. TypeScript also falls back to any where it can't infer a type, such as an unannotated parameter; noImplicitAny turns that into an error: "Parameter 'a' implicitly has an 'any' type."
unknown accepts anything and allows nothing. Like any, every value is assignable to unknown. Unlike any, you can't use the value until you have checked what it is:
const input: unknown = JSON.parse('"hello"');
input.toUpperCase();
// error: 'input' is of type 'unknown'.
if (typeof input === "string") {
input.toUpperCase(); // OK: the check proved it is a string
}That makes unknown the honest type for anything you haven't checked yet: parsed JSON, a message from another window, a caught error.
never has no values. It is the return type of a function that never returns normally, because it always throws, and the type TypeScript gives a value once every possibility has been ruled out:
function fail(message: string): never {
throw new Error(message);
}never is assignable to every type, and no type except never itself is assignable to it. The second property is what exhaustiveness checks are built on: assign a value to never, and the compiler reports any case you forgot to handle.
accepts any value? usable without a check?
any yes yes (nothing is checked)
unknown yes no
never no (it has no values) -A rule that serves well: use unknown at the edges where data enters, and treat every any in a diff as a decision someone has to explain.
Compiler flags that matter
TypeScript-in nə qədər yoxladığı tsconfig.json-dan asılıdır və bunun çox hissəsini bir neçə bayraq həll edir:
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true
}
}strict bütün strict ailəsini qoşur: noImplicitAny, strictNullChecks, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis, useUnknownInCatchVariables, alwaysStrict və strictBuiltinIteratorReturn. TypeScript 6.0-dan bəri strict default halda qoşuludur, amma layihədə o yenə də söndürülmüş ola bilər: məsələn, köhnə konfiqurasiyada "strict": false yazılıb, ya da layihə köhnə TypeScript versiyasındadır. Tiplərə güvənməzdən əvvəl konfiqurasiyanı yoxla.
strictNullChecks ən çox bug tutan bayraqdır. Onsuz null və undefined hər tipə daxildir, ona görə kompilyator sənə dəyərin olmaya biləcəyini deyə bilmir. Onunla isə bunlar ayrıca tiplərdir və onları emal etməlisən:
const root = document.querySelector("#app"); // Element | null
root.textContent = "Ready";
// xəta: 'root' is possibly 'null'.
const big = [1, 2, 3].find((n) => n > 5); // number | undefinedBu xətaların hər biri əks halda icra zamanı baş verəcək bir "Cannot read properties of null"-dur.
noImplicitAny yoxlayıcının səssizcə təslim olmasının qarşısını alır: tipi çıxarıla bilməyən parametr any əvəzinə xəta olur.
noUncheckedIndexedAccess strict-ə daxil deyil. Onsuz massiv elementini və ya record girişini indekslə oxuyanda TypeScript dəyərin həmişə orada olduğunu güman edir:
const scores: Record<string, number> = {};
const ada = scores["ada"]; // number, amma icra zamanı undefined
const names: string[] = [];
const first = names[0]; // string, amma icra zamanı undefinedBayraq qoşulanda bunlar number | undefined və string | undefined olur, yəni çatışmayan halı emal etməli olursan. Bu, bir az səs-küy əlavə edir (indeksli for dövrü də yoxlama tələb edir, for...of isə yox), amma real bug-lar tapır. strict-dən kənarda qalan başqa bir bayraq exactOptionalPropertyTypes-dır: onunla optional color?: string xassəsini yazmamaq olar, amma tip undefined-i ehtiva etmirsə, { color: undefined } xətadır.
Köhnə kod bazasında strict-i qoşmaq yüzlərlə xəta verə bilər. Bayraqları bir-bir qoş, əvvəlcə strictNullChecks-i, və hər xətaya sual kimi bax: bu dəyər burada həqiqətən olmaya bilərmi?
How much TypeScript checks depends on tsconfig.json, and a few flags decide most of it:
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true
}
}strict turns on the whole strict family: noImplicitAny, strictNullChecks, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis, useUnknownInCatchVariables, alwaysStrict and strictBuiltinIteratorReturn. Since TypeScript 6.0, strict is on by default, but a project can still have it off, for example an older config with "strict": false or a project on an older TypeScript version. Check the config before you trust the types.
strictNullChecks catches the most bugs. Without it, null and undefined are allowed in every type, so the compiler can't tell you that a value may be missing. With it, they are separate types you must handle:
const root = document.querySelector("#app"); // Element | null
root.textContent = "Ready";
// error: 'root' is possibly 'null'.
const big = [1, 2, 3].find((n) => n > 5); // number | undefinedEach of those errors is a "Cannot read properties of null" that would otherwise happen at run time.
noImplicitAny stops the checker from quietly giving up: a parameter whose type can't be inferred becomes an error instead of any.
noUncheckedIndexedAccess is not part of strict. Without it, reading an array element or a record entry by index pretends the value is always there:
const scores: Record<string, number> = {};
const ada = scores["ada"]; // number, but undefined at run time
const names: string[] = [];
const first = names[0]; // string, but undefined at run timeWith the flag, these become number | undefined and string | undefined, so you have to handle the missing case. It adds some noise (an indexed for loop needs a check too, while for...of doesn't), and it finds real bugs. exactOptionalPropertyTypes is another opt-in outside strict: with it, an optional color?: string may be left out, but { color: undefined } is an error unless the type includes undefined.
Turning strict on in an old codebase can produce hundreds of errors. Enable the flags one at a time, strictNullChecks first, and treat each error as a question: can this value really be missing here?
Syntax that does not erase
TypeScript sintaksisinin demək olar ki, hamısı yalnız tiplərə aiddir və silinəndə yoxa çıxır. Bir neçə köhnə imkan isə fərqlidir: onlar öz JavaScript kodunu yaradır.
enum Status {
Active,
Banned,
}
namespace Config {
export const retries = 3;
}
class User {
constructor(public name: string) {} // parameter property
}tsc kompilyatoru enum-u addan rəqəmə və rəqəmdən ada girişləri olan obyektə, namespace-i obyekti dolduran funksiyaya, parameter property-ni isə sahəyə və konstruktordakı this.name = name sətrinə çevirir. Bunların heç birini simvolları silməklə almaq olmur, ona görə tipləri yalnız silən alət onları emal edə bilmir. Node-un daxili type stripping-i proqramı işə salmaqdan imtina edir:
SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript enum is not supported in strip-only modeEyni şey import x = require("...") və export = üçün də keçərlidir. Yalnız tiplərdən ibarət namespace isə problem deyil, çünki tam silinir. esbuild və Sucrase kimi transpilyatorlar enum-ları çevirir; bu məhdudiyyət yalnız tipləri silən alətlərə aiddir.
erasableSyntaxOnly
TypeScript 5.8 erasableSyntaxOnly bayrağını əlavə etdi. Onunla tsc bu konstruksiyaları proqram işə düşməyəndə yox, elə redaktorda göstərir ("This syntax is not allowed when 'erasableSyntaxOnly' is enabled."). Buraxılış qeydləri onu verbatimModuleSyntax ilə birlikdə işlətməyi tövsiyə edir; bu bayraq yalnız tip olan importlar üçün import type tələb edir. Bu da eyni səbəbdən vacibdir: tipləri silən alət hər dəfə bir fayla baxır və import olunan adın yalnız tip olduğunu bilə bilmir. Node-un sənədləri xəbərdarlıq edir ki, type açar sözü olmadan o, importu dəyər importu kimi qəbul edir və bu, icra zamanı xəta verir.
Silinə bilən əvəzləyicilər adi JavaScript-dir:
// enum əvəzinə: obyekt və ondan çıxarılan union tip
const Status = { Active: "active", Banned: "banned" } as const;
type Status = (typeof Status)[keyof typeof Status]; // "active" | "banned"
// parameter property əvəzinə: sahə və mənimsətmə
class User {
name: string;
constructor(name: string) {
this.name = name;
}
}Dəyərləri olan namespace əvəzinə ES modulu və onun export-larını işlət.
Bu o demək deyil ki, tsc və ya enum-u dəstəkləyən transpilyatorla build olunan layihədə enum işlətmək səhvdir. Amma Node-da type stripping Node 25.2-dən stabildir və silinə bilən sintaksislə yazılmış kod istənilən alətlə, tipləri yalnız silənlər də daxil olmaqla, işləyir.
Almost all TypeScript syntax is type-only and disappears when it is stripped. A few older features are different: they produce JavaScript of their own.
enum Status {
Active,
Banned,
}
namespace Config {
export const retries = 3;
}
class User {
constructor(public name: string) {} // a parameter property
}tsc compiles the enum into an object with name-to-number and number-to-name entries, the namespace into a function that fills an object, and the parameter property into a field plus this.name = name in the constructor. None of that can be produced by deleting characters, so a tool that only strips types can't handle it. Node's built-in type stripping refuses to start:
SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript enum is not supported in strip-only modeThe same applies to import x = require("...") and export =. A namespace that contains only types is fine, because it erases completely. Transpilers such as esbuild and Sucrase do convert enums; the limit is specific to tools that only strip.
erasableSyntaxOnly
TypeScript 5.8 added the erasableSyntaxOnly flag. With it, tsc reports these constructs in the editor ("This syntax is not allowed when 'erasableSyntaxOnly' is enabled.") instead of letting you find out when the program fails to start. The release notes recommend combining it with verbatimModuleSyntax, which requires import type for imports that are only types. That matters for the same reason: a stripping tool sees one file at a time and can't know that an imported name is only a type. Node's documentation warns that without the type keyword it treats the import as a value import, which fails at run time.
The erasable replacements are ordinary JavaScript:
// Instead of an enum: an object and a union type derived from it
const Status = { Active: "active", Banned: "banned" } as const;
type Status = (typeof Status)[keyof typeof Status]; // "active" | "banned"
// Instead of a parameter property: a field and an assignment
class User {
name: string;
constructor(name: string) {
this.name = name;
}
}Instead of a namespace with values, use an ES module and its exports.
None of this makes enum wrong in a project built by tsc or by a transpiler that supports it. But type stripping in Node is stable since Node 25.2, and code written with erasable syntax works with every tool, strippers included.
Nominal-like types with brands
Struktur tipləşdirmənin bir bədəli var: eyni formalı iki tipi bir-birindən ayırmaq olmur. Type alias-lar kömək etmir, çünki alias eyni tip üçün sadəcə yeni addır:
type UserId = string;
type OrderId = string;
declare function cancelOrder(id: OrderId): void;
declare const userId: UserId;
cancelOrder(userId); // kompilyasiya olunur: hər ikisi sadəcə string-dirBelə dəyərləri qarışdırmaq real riskdirsə (müxtəlif növ obyektlərin id-ləri, müxtəlif valyutalarda məbləğlər, yoxlanmış və yoxlanmamış string), tipləri brend ilə uyğunsuz edə bilərsən: brend yalnız tipdə mövcud olan bir xassə ilə intersection-dır.
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
declare function cancelOrder(id: OrderId): void;
declare const userId: UserId;
function toOrderId(raw: string): OrderId {
if (!/^ord_\d+$/.test(raw)) throw new Error(`Not an order id: ${raw}`);
return raw as OrderId;
}
cancelOrder(toOrderId("ord_17")); // OK
cancelOrder("ord_17"); // xəta: Argument of type 'string' is not assignable to parameter of type 'OrderId'.
cancelOrder(userId); // xəta: Argument of type 'UserId' is not assignable to parameter of type 'OrderId'.Adi string-də __brand yoxdur, iki brendin isə literal tipləri fərqlidir, ona görə heç biri digərinə çevrilmir. Brendli dəyər yenə də string-dir: string gözlənilən hər yerə ötürülə bilir və bütün string metodları ondadır.
Brend sırf tip məlumatıdır. İcra zamanı dəyər elə ilkin string-dir, __brand mövcud deyil və onu heç nə yoxlamır. Ona görə yeganə as toOrderId kimi əvvəlcə yoxlayan funksiyanın içində olmalıdır: kompilyatora "mənə inan" dediyin yeganə yer odur, deməli, iddianı orada doğru et. Brendlər serializasiyadan da sağ çıxmır: JSON.parse-dan və ya serverdən qayıdan id-lər adi string-dir və yenə həmin funksiyadan keçməlidir.
Klasslar isə real nominal yoxlama verir. private və ya #private üzvü olan klass yalnız öz nümunələri (instance) və alt klasslarının nümunələri ilə uyğundur, eyni formalı başqa klassla yox; #field in value isə icra zamanı klassı yoxlayır:
class Cents {
#value: number;
constructor(value: number) {
this.#value = value;
}
static is(x: object): x is Cents {
return #value in x;
}
}Brendlər dəyərlərin yaradıldığı yerlərdə bir az əlavə iş tələb edir. Onları hər string üçün yox, qarışıqlığın baha başa gələcəyi və review-da gözdən qaça biləcəyi yerlərdə işlət.
Structural typing has one cost: two types with the same shape can't be told apart. Type aliases don't help, because an alias is only a new name for the same type:
type UserId = string;
type OrderId = string;
declare function cancelOrder(id: OrderId): void;
declare const userId: UserId;
cancelOrder(userId); // compiles: both are just stringWhen mixing such values up is a real risk (ids of different entities, amounts in different currencies, a string that has been validated and one that hasn't), you can make the types incompatible with a brand: an intersection with a property that exists only in the type.
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
declare function cancelOrder(id: OrderId): void;
declare const userId: UserId;
function toOrderId(raw: string): OrderId {
if (!/^ord_\d+$/.test(raw)) throw new Error(`Not an order id: ${raw}`);
return raw as OrderId;
}
cancelOrder(toOrderId("ord_17")); // OK
cancelOrder("ord_17"); // error: Argument of type 'string' is not assignable to parameter of type 'OrderId'.
cancelOrder(userId); // error: Argument of type 'UserId' is not assignable to parameter of type 'OrderId'.A plain string lacks __brand, and the two brands have different literal types, so neither converts to the other. A branded value is still a string: it can go wherever a string is expected and has every string method.
The brand is pure type information. At run time the value is the original string, __brand doesn't exist, and nothing checks it. So the only as should sit inside a function like toOrderId that validates first: it is the one place where you tell the compiler "trust me", so make the claim true there. Brands don't survive serialisation either: ids that come back from JSON.parse or a server are plain strings and must pass through the same function again.
Classes offer a real nominal check. A class with a private or #private member is compatible only with its own instances and those of its subclasses, not with another class of the same shape, and #field in value tests for the class at run time:
class Cents {
#value: number;
constructor(value: number) {
this.#value = value;
}
static is(x: object): x is Cents {
return #value in x;
}
}Brands add a little ceremony where values are created. Use them where a mix-up would be expensive and hard to spot in review, not for every string in the codebase.
Interview tips
30 saniyəlik cavab. "TypeScript JavaScript üstəgəl tip yoxlayıcısıdır. Kod JavaScript-ə çevriləndə tiplər silinir, ona görə onlar proqramın nə etdiyini heç vaxt dəyişmir və icra zamanı datanı heç vaxt yoxlamır. Uyğunluq struktur əsaslıdır: dəyərdə tələb olunan üzvlər varsa, adından asılı olmayaraq tipə uyğun gəlir; bir əlavə qayda ilə: təzə obyekt literalları tanınmayan xassələrə görə yoxlanır. tsc yoxlayır; Node-un type stripping-i, esbuild və ya Sucrase isə yalnız tipləri silir, ona görə tip yoxlaması CI-da ayrıca addım olmalıdır."
Gözlənilən suallar
- Struktur, yoxsa nominal, və fərq nədir? Adını heç vaxt çəkmədiyi interface-ə uyğun gələn klass göstər, sonra nominal davranış almağın yolu kimi brendləri xatırlat.
- Artıq xassəsi olan obyekt niyə burada xəta verir, orada isə yox? Artıq xassə yoxlaması yalnız təzə obyekt literallarına aiddir.
- Dəyərin
Userolduğunu icra zamanı yoxlamaq olarmı? Interface ilə yox: o silinir.typeofvəinilə yoxlama yaz və ya sxem işlət;instanceofyalnız klasslarla işləyir. interface, yoxsatype? Union-lar və hesablanan tiplərtypetələb edir; interface-lər birləşir vəextendskonfliktlərini göstərir. Komandanın konvensiyasını və onun səbəbini de.any, yoxsaunknown?anyyoxlamanı söndürür;unknownistifadədən əvvəl yoxlamağa məcbur edir.node app.tsbuenum-u niyə qəbul etmir? Node yalnız tipləri silir; enum-lar, dəyərli namespace-lər və parameter property-lər yaradılan kod tələb edir.erasableSyntaxOnlyonları redaktorda göstərir.
Bal itirdən səhvlər
- TypeScript-in kodu "icra zamanı təhlükəsiz" etdiyini və ya API cavablarını yoxladığını demək. O, kodunu sənin öz iddialarına qarşı yoxlayır; kənardan gələn data sən yoxlayana qədər yoxlanmamış qalır.
- Daha dar qaytarma tipini filtr saymaq. O, xassələri
JSON.stringify-dan yox, yalnız yoxlayıcıdan gizlədir. - Layihə build olunursa, tip yoxlamasından da keçdiyini güman etmək.
tsc-ni nəyin işə saldığını soruş. - Strict ailəsini əzbər sadalayıb hansı bayraqların daha vacib olduğunu bilməmək:
strictNullChecks,noImplicitAnyvəstrict-ə daxil olmayannoUncheckedIndexedAccess.
Senior səviyyəni göstərən məqamlar
Tiplərin harada dayandığından danış: datanın daxil olduğu sərhədlər, yoxlayıcını yan keçən as və any, nə qədər yoxlanacağını həll edən tsconfig bayraqları və ümumiyyətlə yoxlanıb-yoxlanmayacağını həll edən pipeline. Böyük kod bazasında id-lər və ya pul üçün brendləri nə vaxt tətbiq edəcəyini və onların qiymətini, yəni belə dəyərlərin yaradıldığı hər yerdə yoxlayan funksiyanı göstər.
A 30-second answer. "TypeScript is JavaScript plus a type checker. Types are erased when the code becomes JavaScript, so they never change what the program does and never check data at run time. Compatibility is structural: a value fits a type when it has the required members, whatever its name, with one extra rule: fresh object literals are checked for unknown properties. tsc checks; Node's type stripping, esbuild or Sucrase only remove types, so the type check has to be its own step in CI."
Questions you are likely to get
- Structural or nominal, and what is the difference? Show a class that fits an interface it never mentions, then mention brands as the way to get nominal behaviour.
- Why does an object with an extra property fail here and pass there? Excess property checks apply only to fresh object literals.
- Can you check at run time that a value is a
User? Not from the interface: it is erased. Write a check withtypeofandin, or use a schema;instanceofworks only for classes. interfaceortype? Unions and computed types needtype; interfaces merge and reportextendsconflicts. Name your team's convention and why.anyorunknown?anydisables checking;unknownforces a check before use.- Why does
node app.tsreject thisenum? Node only strips types; enums, namespaces with values and parameter properties need generated code.erasableSyntaxOnlyreports them in the editor.
Mistakes that cost points
- Saying TypeScript makes code "safe at run time" or validates API responses. It checks your code against your own claims; data from outside stays unchecked until you check it.
- Treating a narrower return type as a filter. It hides properties from the checker, not from
JSON.stringify. - Assuming a project is type-checked because it builds. Ask what runs
tsc. - Reciting the strict family without knowing which flags matter most:
strictNullChecks,noImplicitAny, andnoUncheckedIndexedAccess, whichstrictdoes not include.
Senior signal
Talk about where types stop: the boundaries where data enters, the as and any that bypass the checker, the tsconfig flags that decide how much is checked, and the pipeline that decides whether it is checked at all. Show when you would introduce brands for ids or money in a large codebase, and what they cost: a validating function at every point where such values are created.
What to check when reviewing TypeScript types
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. Tip səhvləri açıq-aşkar üzə çıxmır: kod yenə JavaScript-ə çevrilir və işləyir, səhv fərziyyə isə sonra production-da pis data və ya çökmə kimi görünür.
- CI-da tip yoxlayıcısını nəsə işə salırmı? Tipləri yalnız silən alətlər (Node, esbuild, Sucrase) tip xətaları ilə dolu kodu da build edir və işə salır. Pipeline-da
tsc --noEmit-i və ya tipləri yoxlayan framework build-ini axtar; bir dəfə tipi qəsdən poz və pipeline-ın düşdüyünə əmin ol. - Kənardan gələn data yoxlanmış kimi annotasiya olunubmu?
const user: User = await response.json()və yaJSON.parse(text) as Configheç kimin yoxlamadığı vəddir. Parse olunmuş JSON, storage və URL dəyərləri üzərindəki annotasiyaları vəasifadələrini axtar: icra zamanı yoxlama və ya sxem onları təsdiqləyənə qədər onlarunknownqalmalıdır. - API-yə, loga göndərilən və ya
JSON.stringifyilə çevrilən obyektdə yalnız tipində sadalanan sahələr varmı? Daha dar tip xassələri silmir, ona görə bütövUser-iPublicUserkimi qaytarmaq hər şeyi göndərir. Belə obyektlərin sahə-sahə qurulduğunu yoxla və real payload-a network panelində və ya logda bax. - Diff
any,as any,@ts-ignorevə ya@ts-expect-errorəlavə edirmi? Onların hər biri yoxlayıcını bir dəyər və ya sətir üçün söndürür. Diff-də onları axtar; hər biri şərhdə yazılmış səbəb tələb edir, əvəzində isə adətənunknownvə yoxlama işlətmək mümkündür. tsconfig.jsondəyişibmi?strict,strictNullChecksvə yanoImplicitAny-ni söndürmək xətaları yalnız dəyişən fayllarda yox, bütün layihədə gizlədir. Konfiqurasiyadakı hər dəyişikliyi oxu vətsc --noEmit-i köhnə və yeni parametrlərlə işə sal.- Layihə type stripping ilə işləyirsə, kodda
enum, dəyərli namespace və ya parameter property varmı? Node-un daxili stripping-i onlarda başlanğıcdaERR_UNSUPPORTED_TYPESCRIPT_SYNTAXilə dayanır. Faylı Node ilə işə sal və yaerasableSyntaxOnly-ni qoş ki,tsconları göstərsin.
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. Type mistakes don't fail loudly: the code still becomes JavaScript and runs, and the wrong assumption shows up later as bad data or a crash in production.
- Does something in CI run the type checker? Tools that only strip types (Node, esbuild, Sucrase) build and run code full of type errors. Look for
tsc --noEmit, or a framework build that type-checks, in the pipeline; break a type on purpose once and confirm the pipeline fails. - Is data from outside annotated as if it had been checked?
const user: User = await response.json()orJSON.parse(text) as Configis a promise nobody verifies. Look for annotations andason parsed JSON, storage and URL values: they should stayunknownuntil a runtime check or a schema has validated them. - Does an object sent to an API, a log or
JSON.stringifycontain only the fields its type lists? A narrower type doesn't remove properties, so returning a wholeUseras aPublicUsersends everything. Check that such objects are built field by field, and look at the real payload in the network panel or the log. - Does the diff add
any,as any,@ts-ignoreor@ts-expect-error? Each one switches the checker off for a value or a line. Search the diff for them; each needs a reason in a comment, andunknownplus a check is usually possible instead. - Did
tsconfig.jsonchange? Turning offstrict,strictNullChecksornoImplicitAnyhides errors across the whole project, not just in the changed files. Read every change to the config and runtsc --noEmitwith the old and the new settings. - Does the code use
enum, a namespace with values or parameter properties where the project runs through type stripping? Node's built-in stripping fails on them at startup withERR_UNSUPPORTED_TYPESCRIPT_SYNTAX. Run the file with Node, or turn onerasableSyntaxOnlyso thattscreports them.