Utility, mapped and conditional types
How TypeScript computes types from other types: keyof, typeof and indexed access, the everyday utility types and how they are defined, mapped types with modifiers and key remapping, template literal types, conditional types with infer and distribution, and when type-level code is too clever.
This topic starts at Middle level.
keyof, typeof and indexed access types
Tip çevrilmələrinin çoxu artıq mövcud olan bir şeydən başlayır: dəyərdən və ya başqa tipdən. Üç operator tipi ikinci dəfə yazmaq əvəzinə onu törətməyə imkan verir.
typeof valuetip mövqeyində dəyişənin və ya xassənin tipini verir. Bu, icra zamanı"string"qaytaran JavaScript operatoru yox, tip səviyyəsindəkitypeof-dur və TypeScript ondan yalnız identifikatorlar və onların xassələri üzərində istifadəyə icazə verir.keyof TT-nin açarlarının union-ıdır.T[K], yəni indexed access tipi,Kxassəsinin tipidir.Kunion da ola bilər,T[number]isə massivin və ya tuple-ın element tipini verir.
const config = {
apiUrl: "/api",
retries: 3,
features: { search: true },
};
type Config = typeof config; // { apiUrl: string; retries: number; features: { search: boolean } }
type ConfigKey = keyof typeof config; // "apiUrl" | "retries" | "features"
type Features = Config["features"]; // { search: boolean }
type Scalar = Config["apiUrl" | "retries"]; // string | numberBir siyahı, bir həqiqət mənbəyi
Tez-tez rast gəlinən şablon: icazə verilən dəyərləri proqramın icra zamanı istifadə edə biləcəyi kodda saxla, tipi isə onlardan törət.
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number]; // "admin" | "editor" | "viewer"
function isRole(value: string): value is Role {
return (ROLES as readonly string[]).includes(value);
}as const olmasa, ROLES string[], Role isə sadəcə string olardı. Massivə "owner" əlavə et, tip də onun ardınca dəyişəcək; əllə yazılmış union isə massivdən ayrı düşərdi. isRole eyni siyahı üzərində qurulmuş , ona görə yoxlama ilə tip bir-birinə zidd ola bilməz.
Obyektlər də eyni cür işləyir. const STATUS = { active: "Active", banned: "Banned" } as const olanda keyof typeof STATUS "active" | "banned", (typeof STATUS)[keyof typeof STATUS] isə "Active" | "Banned" olur.
Dəyərlər və tiplər ayrı yerlərdə yaşayır
Indexed access dəyər yox, tip qəbul edir:
const key = "retries";
type Retries = Config[key]; // Error: Type 'key' cannot be used as an index type.
type Retries2 = Config[typeof key]; // numbertypeof kod da icra etmir: typeof createUser("Aysel") sintaksis xətasıdır. Çağırışın nəticəsinin tipi ReturnType<typeof createUser>-dir, aşağıdakı utility tiplərdən biri.
Bu üç operator bu mövzudakı qalan hər şeyin əsasını təşkil edir: daxili utility tiplər keyof və indexed access ilə yazılıb.
Most type transformations start from something that already exists: a value or another type. Three operators let you derive a type instead of writing it a second time.
typeof valuein a type position gives the type of a variable or property. It is the type-leveltypeof, not the JavaScript operator that returns"string"at run time, and TypeScript allows it only on identifiers and their properties.keyof Tis the union ofT's keys.T[K], an indexed access type, is the type of propertyK.Kcan be a union, andT[number]gives the element type of an array or a tuple.
const config = {
apiUrl: "/api",
retries: 3,
features: { search: true },
};
type Config = typeof config; // { apiUrl: string; retries: number; features: { search: boolean } }
type ConfigKey = keyof typeof config; // "apiUrl" | "retries" | "features"
type Features = Config["features"]; // { search: boolean }
type Scalar = Config["apiUrl" | "retries"]; // string | numberOne list, one source of truth
A common pattern: keep the allowed values in code, where the program can use them at run time, and derive the type from them.
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number]; // "admin" | "editor" | "viewer"
function isRole(value: string): value is Role {
return (ROLES as readonly string[]).includes(value);
}Without as const, ROLES would be a string[] and Role would be plain string. Add "owner" to the array and the type follows; a hand-written union would drift away from the array. isRole is a built on the same list, so the check and the type cannot disagree.
Objects work the same way. With const STATUS = { active: "Active", banned: "Banned" } as const, keyof typeof STATUS is "active" | "banned", and (typeof STATUS)[keyof typeof STATUS] is "Active" | "Banned".
Values and types live in different places
Indexed access takes types, not values:
const key = "retries";
type Retries = Config[key]; // Error: Type 'key' cannot be used as an index type.
type Retries2 = Config[typeof key]; // numberAnd typeof does not run code: typeof createUser("Aysel") is a syntax error. The type of a call's result is ReturnType<typeof createUser>, one of the utility types below.
These three operators are the building blocks of everything else in this topic: the built-in utility types are written with keyof and indexed access.
Everyday utility types
TypeScript-in standart kitabxanasındakı, bir tipdən başqasını quran generic tiplərdir. Onlar qlobaldır, heç nə import etmək lazım deyil. Hər gün rastlaşacağın tiplər:
type User = {
id: string;
name: string;
email?: string;
readonly createdAt: Date;
};
type UserPatch = Partial<Omit<User, "id" | "createdAt">>; // { name?: string; email?: string }
type CompleteUser = Required<User>; // email artıq məcburidir
type UserPreview = Pick<User, "id" | "name">; // { id: string; name: string }
type FrozenUser = Readonly<User>; // bütün xassələr readonly-dir
type CountByStatus = Record<"draft" | "published", number>; // { draft: number; published: number }
type Name = NonNullable<string | null | undefined>; // stringPartial<T>bütün xassələri məcburi olmayan edir: yeniləmə payload-ları, form qaralamaları, test factory-lərində override-lar.Required<T>bütün xassələrdən?-ı silir: default-lar doldurulduqdan sonrakı konfiqurasiya.Readonly<T>bütün xassələrireadonlyedir: ötürdüyün, amma dəyişməməli olduğun data. O, yalnız tip yoxlayıcısı üçün mövcuddur; obyekti dondurmur.Pick<T, K>sadalanan açarları saxlayır,Omit<T, K>isə qalanların hamısını.Pickböyük tipin kiçik görünüşünü verir,Omitisə "server-in yaratdığı sahələr olmadan eyni şeyi".Record<K, V>açarlarıK, dəyərləriVolan obyekt tipidir. Literal açarlardan ibarət union ilə hər açar məcburidir, bu da onu bütün halları əhatə edən yaxşı cədvələ (lookup table) çevirir.NonNullable<T>nullvəundefined-i silir.
Bütün halları əhatə edən cədvəl
type Status = "draft" | "review" | "published";
const statusLabel: Record<Status, string> = { // Error
draft: "Draft",
review: "In review",
};Xəta belədir: "Property 'published' is missing in type '{ draft: string; review: string; }' but required in type 'Record<Status, string>'." Union-a yeni status əlavə et, kod bazasındakı hər Record<Status, …> yeni halı əlavə edənə qədər kompilyasiya olunmayacaq. { [key: string]: string } kimi tiplənmiş adi obyekt bunu heç vaxt deməzdi.
Birləşdir, sonra nəticəyə ad ver
Utility tiplər iç-içə yazılır. Partial<Omit<User, "id" | "createdAt">> içəridən çölə oxunur: "id və createdAt-sız User, hər şey məcburi olmayan". Nəticə birdən çox yerdə işlənirsə, ona UserPatch kimi ad ver ki, hover və xəta mesajları ifadəni yox, adı göstərsin.
Hamısının mənası odur ki, törədilmiş tip orijinalın ardınca gedir. User-ə phone?: string əlavə et: UserPatch telefonu da qəbul edəcək, UserPreview isə açarlarını sadaladığı üçün olduğu kimi qalacaq. Köçürülmüş tip isə səssizcə geridə qalardı.
are generic types from TypeScript's standard library that build one type from another. They are global, so there is nothing to import. The ones you meet every day:
type User = {
id: string;
name: string;
email?: string;
readonly createdAt: Date;
};
type UserPatch = Partial<Omit<User, "id" | "createdAt">>; // { name?: string; email?: string }
type CompleteUser = Required<User>; // email is no longer optional
type UserPreview = Pick<User, "id" | "name">; // { id: string; name: string }
type FrozenUser = Readonly<User>; // every property readonly
type CountByStatus = Record<"draft" | "published", number>; // { draft: number; published: number }
type Name = NonNullable<string | null | undefined>; // stringPartial<T>makes every property optional: update payloads, form drafts, overrides in test factories.Required<T>removes?from every property: a config after the defaults have been filled in.Readonly<T>marks every propertyreadonly: data you pass around but must not change. It exists only for the type checker; it does not freeze the object.Pick<T, K>keeps the listed keys,Omit<T, K>keeps all the others.Pickgives a small view of a big type;Omitgives "the same thing without the fields the server generates".Record<K, V>is an object type with keysKand valuesV. With a union of literal keys every key is required, which makes it a good exhaustive lookup table.NonNullable<T>removesnullandundefined.
An exhaustive lookup table
type Status = "draft" | "review" | "published";
const statusLabel: Record<Status, string> = { // Error
draft: "Draft",
review: "In review",
};The error says "Property 'published' is missing in type '{ draft: string; review: string; }' but required in type 'Record<Status, string>'." Add a status to the union, and every Record<Status, …> in the codebase stops compiling until it handles the new case. A plain object typed { [key: string]: string } would never tell you.
Compose, then name the result
Utility types nest. Partial<Omit<User, "id" | "createdAt">> reads from the inside out: "a User without id and createdAt, everything optional". When the result is used in more than one place, give it a name such as UserPatch, so hovers and error messages show the name instead of the expression.
The point of all of them is that the derived type follows the original. Add phone?: string to User, and UserPatch accepts a phone too, while UserPreview stays as it is because it lists its keys. A copied type would stay behind silently.
Types from functions: ReturnType, Parameters, Awaited
Funksiya artıq bir formanı müəyyən edirsə, tipi ikinci dəfə elan etmək əvəzinə onu funksiyadan törət. Bu utility-lər funksiyanın tipini qəbul edir, ona görə onlara typeof fn ötürürsən:
function createCart(ownerId: string, currency: "AZN" | "EUR" = "AZN") {
return { ownerId, currency, items: [] as CartItem[], createdAt: new Date() };
}
type Cart = ReturnType<typeof createCart>;
// { ownerId: string; currency: "AZN" | "EUR"; items: CartItem[]; createdAt: Date }
type CartArgs = Parameters<typeof createCart>;
// [ownerId: string, currency?: "AZN" | "EUR"]
type Currency = Parameters<typeof createCart>[1]; // "AZN" | "EUR" | undefinedParameters tuple verir, ona görə bir parametri almaq üçün onu ədədlə indeksləyirsən. Məcburi olmayan parametrlər məcburi olmayan qalır, Currency-yə undefined-in daxil olmasının səbəbi budur.
Async funksiyalar üçün Awaited
async funksiyanın qaytarma tipi Promise-dir. Awaited<T> onu await-in etdiyi kimi açır: rekursiv şəkildə və promise olmayan dəyərlərə toxunmadan.
async function loadDashboard(userId: string) {
const [user, orders] = await Promise.all([getUser(userId), getOrders(userId)]);
return { user, orders };
}
type DashboardPromise = ReturnType<typeof loadDashboard>; // Promise<{ user: User; orders: Order[] }>
type Dashboard = Awaited<ReturnType<typeof loadDashboard>>; // { user: User; orders: Order[] }
type Nested = Awaited<Promise<Promise<number>>>; // number
type Mixed = Awaited<boolean | Promise<number>>; // number | booleanNə vaxt işlətməli
- Qaytarma tipi export olunmayan kitabxana funksiyası: formasını köçürmək əvəzinə
ReturnType<typeof createClient>. - Arqumentləri dəyişmədən ötürən wrapper:
function withRetry(...args: Parameters<typeof send>). - Forması onu quran kodla müəyyən olunan factory və ya store.
İki qeyd. Overload olunmuş funksiya üçün ReturnType və Parameters handbook-un qeyd etdiyi kimi yalnız sonuncu imzanı görür; overload-u sənin yerinə seçə bilmir. Bir də, implementasiyadan törədilmiş tip implementasiya dəyişəndə, heç kim bunu qərara almadan dəyişir. Daxili köməkçi üçün bu rahatdır. Başqa modulların asılı olduğu funksiya üçün isə açıq yazılmış, adlı qaytarma tipi qəsdən dəyişdirdiyin müqavilədir və gövdədə onu pozan dəyişiklik elə edildiyi yerdə xəta verir.
When a function already defines a shape, derive the type from the function instead of declaring it twice. These utilities take a function type, so you pass them typeof fn:
function createCart(ownerId: string, currency: "AZN" | "EUR" = "AZN") {
return { ownerId, currency, items: [] as CartItem[], createdAt: new Date() };
}
type Cart = ReturnType<typeof createCart>;
// { ownerId: string; currency: "AZN" | "EUR"; items: CartItem[]; createdAt: Date }
type CartArgs = Parameters<typeof createCart>;
// [ownerId: string, currency?: "AZN" | "EUR"]
type Currency = Parameters<typeof createCart>[1]; // "AZN" | "EUR" | undefinedParameters gives a tuple, so you index it with a number to get one parameter. Optional parameters stay optional, which is why Currency includes undefined.
Awaited for async functions
The return type of an async function is a Promise. Awaited<T> unwraps it the way await does: recursively, and leaving values that are not promises alone.
async function loadDashboard(userId: string) {
const [user, orders] = await Promise.all([getUser(userId), getOrders(userId)]);
return { user, orders };
}
type DashboardPromise = ReturnType<typeof loadDashboard>; // Promise<{ user: User; orders: Order[] }>
type Dashboard = Awaited<ReturnType<typeof loadDashboard>>; // { user: User; orders: Order[] }
type Nested = Awaited<Promise<Promise<number>>>; // number
type Mixed = Awaited<boolean | Promise<number>>; // number | booleanWhen to reach for them
- A library function whose return type is not exported:
ReturnType<typeof createClient>instead of copying its shape. - A wrapper that passes arguments through unchanged:
function withRetry(...args: Parameters<typeof send>). - A factory or a store whose shape is defined by the code that builds it.
Two caveats. For an overloaded function, ReturnType and Parameters see only the last signature, as the handbook notes; they cannot pick an overload for you. And a type derived from an implementation changes whenever the implementation does, without anyone deciding it should. For an internal helper that is convenient. For a function other modules depend on, an explicit, named return type is a contract you change on purpose, and a change in the body that breaks it fails where it was made.
Mapped types
obyekt tipini açarlar union-ı üzrə dövr edərək qurur, map-in massiv üzrə dövr etdiyi kimi. Partial, Required, Readonly, Pick və Record mapped tiplərdir. Standart kitabxana onlardan üçünü belə təyin edir:
type Partial<T> = { [P in keyof T]?: T[P] };
type Required<T> = { [P in keyof T]-?: T[P] };
type Readonly<T> = { readonly [P in keyof T]: T[P] };[P in keyof T]: T[P]-ni belə oxu: "T-nin hər P açarı üçün eyni tipli P xassəsi". Hissələri:
P in Keysunion üzrə dövr edir:keyof Tvə ya istənilən sətir literalları union-ı,Record<K, T>-nin[P in K]: Tilə etdiyi kimi.?vəreadonlyhər xassəyə modifikator əlavə edir.-prefiksi isə onu silir:-?xassələri məcburi,-readonlyisə yazıla bilən edir. Prefiks yoxdursa,+nəzərdə tutulur.- Açarlar
keyof T-dən gələndə mövcud modifikatorlar saxlanır. Məcburi olmayanemail-i olan tip üzrə map etsən,-?yazmadıqcaemailməcburi olmayan qalır.
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type FieldErrors<T> = { [K in keyof T]?: string };
type SignupErrors = FieldErrors<{ email: string; password: string }>;
// { email?: string; password?: string }as ilə açarların yenidən adlandırılması
TypeScript 4.1-dən bəri as ifadəsi map edərkən açarların adını dəyişir. Template literal tiplə birlikdə yeni adlar yarada bilir:
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
type UserGetters = Getters<{ name: string; age: number }>;
// { getName: () => string; getAge: () => number }keyof T & string yalnız sətir açarlarını saxlayır, çünki Capitalize sətir tələb edir, keyof-da isə number və symbol açarları da ola bilər.
Açarı never-ə çevirmək onu atır, bu da mapped tipi filtrə çevirir:
type StringFields<T> = {
[K in keyof T as T[K] extends string ? K : never]: T[K];
};
type Text = StringFields<{ id: number; title: string; body: string }>;
// { title: string; body: string }T[K] extends string ? K : never conditional tipdir: xassə sətirdirsə açarı saxlayır, əks halda never verir.
Bir tip digərini açar-açar izləməlidirsə, mapped tiplər düzgün alətdir: hər form sahəsi üçün xəta, hər event üçün handler, hər resurs üçün yüklənmə bayrağı. Sənə yalnız bir neçə sabit açar lazımdırsa, onları sadəcə yaz.
A builds an object type by iterating over a union of keys, the way map iterates over an array. Partial, Required, Readonly, Pick and Record are all mapped types. This is how the standard library defines three of them:
type Partial<T> = { [P in keyof T]?: T[P] };
type Required<T> = { [P in keyof T]-?: T[P] };
type Readonly<T> = { readonly [P in keyof T]: T[P] };Read [P in keyof T]: T[P] as "for each key P of T, a property P of the same type". The pieces:
P in Keysiterates over a union:keyof T, or any union of string literals, asRecord<K, T>does with[P in K]: T.?andreadonlyadd a modifier to every property. A-prefix removes it instead:-?makes properties required,-readonlymakes them writable. No prefix means+.- When the keys come from
keyof T, the existing modifiers are kept. Mapping over a type with an optionalemailkeepsemailoptional unless you write-?.
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type FieldErrors<T> = { [K in keyof T]?: string };
type SignupErrors = FieldErrors<{ email: string; password: string }>;
// { email?: string; password?: string }Key remapping with as
Since TypeScript 4.1, an as clause renames keys while mapping. With a template literal type it can generate new names:
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
type UserGetters = Getters<{ name: string; age: number }>;
// { getName: () => string; getAge: () => number }keyof T & string keeps only the string keys, because Capitalize needs a string and keyof may also contain number and symbol keys.
Remapping a key to never drops it, which turns a mapped type into a filter:
type StringFields<T> = {
[K in keyof T as T[K] extends string ? K : never]: T[K];
};
type Text = StringFields<{ id: number; title: string; body: string }>;
// { title: string; body: string }T[K] extends string ? K : never is a conditional type: it keeps the key when the property is a string and gives never otherwise.
Mapped types are the right tool when one type must follow another key by key: errors per form field, a handler per event, a loading flag per resource. If you only need a few fixed keys, write them out.
Pitfalls of the built-in utility types
Daxili utility tiplər qısa təriflərdir və onların kənar halları elə bu təriflərdən irəli gəlir.
Omit açarlarını yoxlamır
type Post = { id: string; title: string; publishedAt: Date };
type Draft = Omit<Post, "publishedAtt">; // xəta yoxdur: publishedAt hələ də var
type Preview = Pick<Post, "titel">; // Error: Type '"titel"' does not satisfy the constraint 'keyof Post'.Pick<T, K extends keyof T> açarları yoxlayır; Omit<T, K extends keyof any> isə istənilən sətri qəbul edir, ona görə yazı səhvi və ya adı dəyişdirilmiş sahə heç nəyi silmir və bunu heç kim görmür. Kod bazana bu yoxlama lazımdırsa, bir sətirlik type StrictOmit<T, K extends keyof T> = Omit<T, K> onu əlavə edir.
Pick və Omit union-ları düzləşdirir
type Shape =
| { kind: "circle"; radius: number; id: string }
| { kind: "square"; size: number; id: string };
type NewShape = Omit<Shape, "id">; // { kind: "circle" | "square" }Union-ın keyof-u yalnız bütün üzvlərin ortaq açarlarını ehtiva edir, ona görə Omit kind-ı saxlayır, radius və size-ı isə itirir. yox olur. Omit-i hər üzvə ayrıca tətbiq et, union-ın hər üzvü üçün bir dəfə işləyən conditional tiplə:
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
type NewShape2 = DistributiveOmit<Shape, "id">;
// { kind: "circle"; radius: number } | { kind: "square"; size: number }Readonly dayazdır və yalnız tipdir
Readonly<Settings> settings.theme = "light" yazmağa imkan vermir, amma settings.tags.push("x") yenə kompilyasiya olunur, çünki Readonly dayazdır (shallow): yalnız yuxarı səviyyəli xassələri əhatə edir, içəridəki massiv isə readonly deyil. İcra zamanı da heç nə dəyişmir: obyekt dondurulmur və onu adi Settings kimi alan kod dəyişə bilər. İç-içə massivlər üçün readonly string[] və ya ReadonlyArray, icra zamanı qorunma lazımdırsa Object.freeze işlət (o da dayazdır).
Partial undefined qəbul edir
strict rejimində belə Partial<User> { email: undefined } qəbul edir. İstifadəçi obyektinə spread olunanda o, email-in üzərinə undefined yazır, nəticə isə yenə User kimi tiplənir. strict-in daxil etmədiyi exactOptionalPropertyTypes seçimi "yoxdur" ilə "undefined"-i fərqləndirir və belə çağırış kompilyasiya olunmur.
Record<string, T> hər açarın mövcud olduğunu iddia edir
const prices: Record<string, number> olanda armud olmasa belə prices["pear"] number-dir. Partial<Record<string, number>> (oxunuş number | undefined verir), Map işlət və ya noUncheckedIndexedAccess-i aç.
The built-in utility types are short definitions, and their edge cases follow from those definitions.
Omit does not check its keys
type Post = { id: string; title: string; publishedAt: Date };
type Draft = Omit<Post, "publishedAtt">; // no error: still has publishedAt
type Preview = Pick<Post, "titel">; // Error: Type '"titel"' does not satisfy the constraint 'keyof Post'.Pick<T, K extends keyof T> checks the keys; Omit<T, K extends keyof any> accepts any string, so a typo or a renamed field removes nothing and nobody notices. If your codebase wants the check, a one-line type StrictOmit<T, K extends keyof T> = Omit<T, K> adds it.
Pick and Omit flatten unions
type Shape =
| { kind: "circle"; radius: number; id: string }
| { kind: "square"; size: number; id: string };
type NewShape = Omit<Shape, "id">; // { kind: "circle" | "square" }keyof of a union contains only the keys all members share, so Omit keeps kind and loses radius and size. The is gone. Apply Omit to each member instead, with a conditional type that runs once per member of the union:
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
type NewShape2 = DistributiveOmit<Shape, "id">;
// { kind: "circle"; radius: number } | { kind: "square"; size: number }Readonly is shallow and only a type
Readonly<Settings> stops settings.theme = "light", but settings.tags.push("x") still compiles, because the array inside is not readonly. Nothing changes at run time either: the object is not frozen, and code that receives it as a plain Settings can modify it. Use readonly string[] or ReadonlyArray for nested arrays, and Object.freeze when you need run-time protection (it is shallow too).
Partial accepts undefined
Even under strict, Partial<User> accepts { email: undefined }. Spread into a user, it overwrites the email with undefined, and the result is still typed User. The exactOptionalPropertyTypes option, which strict does not include, makes "missing" and "undefined" different, so that call stops compiling.
Record<string, T> claims every key exists
const prices: Record<string, number> makes prices["pear"] a number, even when there is no pear. Use Partial<Record<string, number>> (reads give number | undefined), a Map, or turn on noUncheckedIndexedAccess.
Template literal types
Template literal tiplər JavaScript-in template sətir sintaksisini tip mövqeyində işlədir. Literal tiplərlə yeni literallar qurur, union-larla isə bütün kombinasiyaları:
type Size = "sm" | "md" | "lg";
type Tone = "primary" | "danger";
type ButtonClass = `btn-${Tone}-${Size}`;
// "btn-primary-sm" | "btn-primary-md" | "btn-primary-lg" | "btn-danger-sm" | ...
type Px = `${number}px`;
const width: Px = "12px"; // OK
const height: Px = "12em"; // Error: Type '"12em"' is not assignable to type '`${number}px`'.
type UserPath = `/users/${string}`;${number} və ${string} şablondur: istənilən ədəd, istənilən sətir. Union bir neçə mövqedə olanda bütün kombinasiyalar alınır, ButtonClass-da göründüyü kimi: 2 ton və 3 ölçü 2 × 3 = 6 üzv verir.
TypeScript-də kompilyatorun özünün reallaşdırdığı dörd daxili sətir tipi də var: Uppercase, Lowercase, Capitalize və Uncapitalize. Onlar adlandırma qaydalarını yoxlanıla bilən edir:
type HandlerName<E extends string> = `on${Capitalize<E>}`;
type Handlers = HandlerName<"click" | "focus">; // "onClick" | "onFocus"infer ilə sətirləri hissələrə ayırmaq
Conditional tipdə template literal şablon kimi işləyir, infer isə hissələri tutur. Bu tip, tiplənmiş router-lərin etdiyi kimi, marşrut yolundan parametr adlarını oxuyur:
type RouteParams<S extends string> =
S extends `${string}:${infer Param}/${infer Rest}`
? Param | RouteParams<`/${Rest}`>
: S extends `${string}:${infer Param}`
? Param
: never;
type Params = RouteParams<"/users/:userId/posts/:postId">; // "userId" | "postId"
type None = RouteParams<"/about">; // neverTip rekursivdir: hər addımda ilk :param-ı götürür və yolun qalanı üçün özünü çağırır.
Union-ları kiçik saxla
Kombinasiyaların sayı sürətlə artır. Hər birində on variant olan üç mövqe 1000 üzv verir və tip yoxlayıcısı dəyərləri onların hamısı ilə müqayisə edir. Müəyyən həddən sonra TypeScript "Expression produces a union type that is too complex to represent." xətası ilə dayanır. Handbook böyük sətir union-larını tiplərdə hesablamaq əvəzinə əvvəlcədən generasiya etməyi tövsiyə edir; template literal tiplər bir neçə üzvlə ən yaxşı işləyir: class adı variantları, event və handler adları, marşrut şablonları, CSS vahidləri.
Template literal types use JavaScript's template string syntax in type positions. With literal types they build new literals; with unions they build every combination:
type Size = "sm" | "md" | "lg";
type Tone = "primary" | "danger";
type ButtonClass = `btn-${Tone}-${Size}`;
// "btn-primary-sm" | "btn-primary-md" | "btn-primary-lg" | "btn-danger-sm" | ...
type Px = `${number}px`;
const width: Px = "12px"; // OK
const height: Px = "12em"; // Error: Type '"12em"' is not assignable to type '`${number}px`'.
type UserPath = `/users/${string}`;${number} and ${string} are patterns: any number, any string. Unions in several positions are cross-multiplied, as ButtonClass shows: 2 tones times 3 sizes is 6 members.
TypeScript also has four built-in string types that the compiler implements itself: Uppercase, Lowercase, Capitalize and Uncapitalize. They make naming conventions checkable:
type HandlerName<E extends string> = `on${Capitalize<E>}`;
type Handlers = HandlerName<"click" | "focus">; // "onClick" | "onFocus"Taking strings apart with infer
In a conditional type, a template literal works as a pattern, and infer captures the parts. This type reads the parameter names out of a route path, the way typed routers do:
type RouteParams<S extends string> =
S extends `${string}:${infer Param}/${infer Rest}`
? Param | RouteParams<`/${Rest}`>
: S extends `${string}:${infer Param}`
? Param
: never;
type Params = RouteParams<"/users/:userId/posts/:postId">; // "userId" | "postId"
type None = RouteParams<"/about">; // neverIt is recursive: each step takes the first :param and calls itself on the rest of the path.
Keep the unions small
Cross-multiplication grows fast. Three positions with ten options each give 1,000 members, and the checker compares values against all of them. Past a limit, TypeScript gives up with "Expression produces a union type that is too complex to represent." The handbook recommends generating large string unions ahead of time instead of computing them in types, and template literal types are at their best with a handful of members: class name variants, event and handler names, route patterns, CSS units.
Conditional types and infer
iki tip arasında seçim edir: T extends U ? X : Y T U-ya mənimsədilə bilirsə X, əks halda Y olur. Konkret tiplə dərhal həll olunur; tip parametri ilə isə parametr məlum olana qədər gözləyir.
type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<"hello">; // "yes"
type B = IsString<number>; // "no"Tək başına bu, tip səviyyəsində if-dir. Conditional tiplər infer ilə faydalı olur.
infer: tiplər üzərində şablon uyğunluğu
extends hissəsinin içində infer X tip dəyişəni elan edir və TypeScript onu uyğunluqdan doldurur. Standart kitabxana tipləri hissələrə belə ayırır:
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;"T funksiyadırsa, onun qaytarma tipini R adlandır və mənə R-i ver." Eyni şablon sənin öz tiplərin üçün də işləyir:
type ElementType<T> = T extends readonly (infer U)[] ? U : T;
type E1 = ElementType<string[]>; // string
type E2 = ElementType<string>; // string
type PropsOf<C> = C extends (props: infer P) => unknown ? P : never;
type ButtonProps = PropsOf<typeof Button>; // funksiya komponentinin props tipi
type Unwrap<T> = T extends Promise<infer V> ? V : T;
type U1 = Unwrap<Promise<Promise<number>>>; // Promise<number>: yalnız bir səviyyəUnwrap bir səviyyədən sonra dayanır, çünki özünü çağırmır; daxili Awaited isə rekursivdir, ona görə Awaited<Promise<Promise<number>>> number-dir.
Hədd: conditional qaytarma tipli generic funksiyalar
Conditional qaytarma tipi dəqiq imza kimi görünür, amma funksiyanın gövdəsi onu ödəyə bilmir:
function label<T extends string | number>(value: T): T extends string ? "text" : "number" {
return typeof value === "string" ? "text" : "number"; // Error: Type '"text"' is not assignable to type 'T extends string ? "text" : "number"'.
}typeof value === "string" T-ni yox, value-nu daraldır, ona görə TypeScript hansı budağın keçərli olduğuna qərar verə bilmir və tip funksiyanın içində həll olunmamış qalır. Adi cavablar: hər hal üçün bir funksiya overload-u və ya yaxşı test olunmuş yerdə tək bir assertion. Bu qədər kiçik funksiya üçün çağıranların bu dəqiqliyə ümumiyyətlə ehtiyacı olub-olmadığını soruş; "text" | "number" qaytarma tipi dürüstdür və heç bir hiylə tələb etmir.
A chooses between two types: T extends U ? X : Y is X when T is assignable to U, and Y otherwise. With a concrete type it resolves at once; with a type parameter it waits until the parameter is known.
type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<"hello">; // "yes"
type B = IsString<number>; // "no"On its own that is a type-level if. Conditional types become useful with infer.
infer: pattern matching on types
Inside the extends clause, infer X declares a type variable that TypeScript fills in from the match. This is how the standard library takes types apart:
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;"If T is a function, call its return type R and give me R." The same pattern works for your own types:
type ElementType<T> = T extends readonly (infer U)[] ? U : T;
type E1 = ElementType<string[]>; // string
type E2 = ElementType<string>; // string
type PropsOf<C> = C extends (props: infer P) => unknown ? P : never;
type ButtonProps = PropsOf<typeof Button>; // the props type of a function component
type Unwrap<T> = T extends Promise<infer V> ? V : T;
type U1 = Unwrap<Promise<Promise<number>>>; // Promise<number>: one level onlyUnwrap stops after one level because it does not call itself; the built-in Awaited is recursive, so Awaited<Promise<Promise<number>>> is number.
The limit: generic functions with conditional return types
A conditional return type looks like a precise signature, but the body cannot satisfy it:
function label<T extends string | number>(value: T): T extends string ? "text" : "number" {
return typeof value === "string" ? "text" : "number"; // Error: Type '"text"' is not assignable to type 'T extends string ? "text" : "number"'.
}typeof value === "string" narrows value, not T, so TypeScript cannot decide which branch applies and the type stays unresolved inside the function. The usual answers are function overloads, one per case, or a single assertion in a well-tested place. For a function this small, ask whether callers need the precision at all; a return type of "text" | "number" is honest and needs no tricks.
Distribution over unions
Yoxlanılan tip sadə tip parametri olanda və ona union ötürəndə, conditional tip hər üzvə ayrıca tətbiq olunur və nəticələr yeni union-da birləşir:
type ToArray<T> = T extends unknown ? T[] : never;
type A = ToArray<string | number>; // string[] | number[], (string | number)[] yoxHandbook bunu distributive conditional tip adlandırır və Exclude ilə Extract-ı işlədən də budur:
type Exclude<T, U> = T extends U ? never : T;
type Extract<T, U> = T extends U ? T : never;
type Events = "click" | "focus" | "blur";
type NoBlur = Exclude<Events, "blur">; // "click" | "focus"Hər üzv ayrıca yoxlanılır; never-ə çevrilənlər yox olur, çünki never boş union-dır.
Paylanmanı söndürmək
Paylanma yalnız yoxlanılan tip bükülməmiş (naked) tip parametri olanda baş verir. Union-ı bütöv yoxlamaq üçün extends-in hər iki tərəfini bir elementli tuple-a sar:
type ToArrayAll<T> = [T] extends [unknown] ? T[] : never;
type B = ToArrayAll<string | number>; // (string | number)[]
type IsString<T> = T extends string ? "yes" : "no";
type IsOnlyString<T> = [T] extends [string] ? "yes" : "no";
type C = IsString<string | number>; // "yes" | "no"
type D = IsOnlyString<string | number>; // "no"İki sürpriz
booleantrue | false-dur, ona görə o da paylanır: paylanan mövqedəboolean extends true ? … : …hər iki budağı verir.neverboş union-dır, ona görə onun üzrə paylanma budaqlardan heç birini yox,neververir:
type IsNever<T> = T extends never ? true : false;
type E = IsNever<never>; // never
type IsNeverFixed<T> = [T] extends [never] ? true : false;
type F = IsNeverFixed<never>; // trueHansı sənə lazımdır
Hər üzvü çevirəndə paylanma düzgündür: Exclude, Extract, discriminated union-ı bütöv saxlayan Omit, hər event üçün handler tipi. Tip haqqında bütövlükdə sual verəndə parametri [ ]-yə sar: o never-dirmi, dəqiq string-dirmi, ümumiyyətlə union-dırmı. Əllə yazılmış conditional tiplərin çaşdırıcı nəticələrinin çoxu tipin bu ikisindən hansını etdiyini unutmaqdan yaranır; nəticə səni təəccübləndirirsə, yoxlanılan tipin sadə tip parametri olub-olmadığına bax.
When the checked type is a bare type parameter and you pass it a union, a conditional type is applied to each member separately, and the results are joined into a new union:
type ToArray<T> = T extends unknown ? T[] : never;
type A = ToArray<string | number>; // string[] | number[], not (string | number)[]The handbook calls this a distributive conditional type, and it is what makes Exclude and Extract work:
type Exclude<T, U> = T extends U ? never : T;
type Extract<T, U> = T extends U ? T : never;
type Events = "click" | "focus" | "blur";
type NoBlur = Exclude<Events, "blur">; // "click" | "focus"Each member is checked on its own; the ones that map to never disappear, because never is the empty union.
Turning it off
Distribution happens only when the checked type is a naked type parameter. Wrap both sides of extends in a one-element tuple to check the union as a whole:
type ToArrayAll<T> = [T] extends [unknown] ? T[] : never;
type B = ToArrayAll<string | number>; // (string | number)[]
type IsString<T> = T extends string ? "yes" : "no";
type IsOnlyString<T> = [T] extends [string] ? "yes" : "no";
type C = IsString<string | number>; // "yes" | "no"
type D = IsOnlyString<string | number>; // "no"Two surprises
booleanistrue | false, so it distributes too:boolean extends true ? … : …in a distributive position gives both branches.neveris an empty union, so distributing over it givesnever, not either branch:
type IsNever<T> = T extends never ? true : false;
type E = IsNever<never>; // never
type IsNeverFixed<T> = [T] extends [never] ? true : false;
type F = IsNeverFixed<never>; // trueWhich one you want
Distribution is right when you transform each member: Exclude, Extract, an Omit that keeps a discriminated union intact, a handler type per event. Wrap the parameter in [ ] when you ask a question about the type as a whole: is it never, is it exactly string, is it a union at all. Many confusing results from hand-written conditional types come from forgetting which of the two a type does; when a result surprises you, check whether the checked type is a bare type parameter.
When type-level code is too clever
Tip səviyyəsində kod da koddur. Kimsə onu oxumalı, kompilyator onu icra etməli olur, yaratdığı xətalar isə başqalarının qarşısına çıxır. Düzgün tiplər də pis seçim ola bilər.
Qiyməti nədir
- Oxunaqlılıq. Bu tip obyektin bütün nöqtəli yollarını verir, məsələn
"a" | "a.b" | "a.b.c":
type Paths<T> = T extends object
? { [K in keyof T & string]: K | `${K}.${Paths<T[K]>}` }[keyof T & string]
: never;O, eyni anda conditional tip, mapped tip, indexed access, template literal və rekursiya işlədir. Komanda yoldaşlarının çoxu onu çağıra bilər; azı onu təhlükəsiz dəyişə bilər.
- Xəta mesajları. Səhv çağırış niyyəti yox, hesablanmış tipi göstərir:
Paths<Config>gözlənilən yerə"a.b.x"ötürmək xəta verir, çünki o, bütün düzgün yolların union-ına mənimsədilə bilmir. Kiçik konfiqurasiya üçün bu normaldır; böyük konfiqurasiyada isə mesaj yollardan ibarət divara çevrilir. - Kompilyasiya vaxtı və hədlər. Hər instantiation tip yoxlayıcısı üçün işdir və redaktor bunu hər düymə basılanda təkrarlayır. Dərin rekursiya "Type instantiation is excessively deep and possibly infinite." xətası ilə dayanır.
tsc --extendedDiagnosticsinstantiation sayını və yoxlama vaxtını çap edir,tsc --generateTrace <dir>isə hansı tiplərin yavaş olduğunu göstərən trace yazır. - Yalançı əminlik. Hesablanmış tip icra zamanı kodun nə etməli olduğunu təsvir edir; onlar arasındakı əlaqə çox vaxt
return out as Getters<T>kimi cast olur və onu heç nə yoxlamır. İmplementasiyadakı səhv dəqiq görünən tipin arxasında gözdən qaçır.
Əvəzində nə etməli
- Tipin hansı bug-ın qarşısını aldığını soruş. Beş marşrutdan ibarət əllə yazılmış union, sadə
stringüstəgəl bir icra zamanı yoxlaması və ya adlı obyekt tipi eyni səhvləri tutursa, onu seç. - Mürəkkəb tipləri bir yerdə saxla, adətən ortaq modulda və ya kitabxana sərhədində, tətbiq kodu isə onları adla işlətsin.
- Hər şeyi bir ifadəyə yığmaq əvəzinə aralıq addımlara ad ver (
type Keys = …,type Mapped = …) və giriş-çıxış nümunəsi olan şərh yaz. - Tipləri test et: kompilyasiya olunmalı çağırışlar və olunmamalı,
// @ts-expect-errorilə işarələnmiş çağırışlar, CI-datscilə yoxlanılsın. Cast-ın arxasındakı icra zamanı kodu da test et.
Bir çox komanda üçün işləyən sərhəd belədir və bu, dilin qaydası yox, mühakimə məsələsidir: real səhvləri tutduğu kənarlarda dəqiq tiplər, insanların hər gün kodu oxuyub dəyişdiyi ortada isə sadə tiplər.
Type-level code is code. Someone has to read it, the compiler has to run it, and the errors it produces land on other people. Correct types can still be a bad trade.
What it costs
- Readability. This type produces every dotted path of an object, such as
"a" | "a.b" | "a.b.c":
type Paths<T> = T extends object
? { [K in keyof T & string]: K | `${K}.${Paths<T[K]>}` }[keyof T & string]
: never;It uses a conditional type, a mapped type, indexed access, a template literal and recursion at once. Most teammates can call it; few can change it safely.
- Error messages. A wrong call reports the computed type, not the intent: passing
"a.b.x"where aPaths<Config>is expected fails because it is not assignable to the union of every valid path. For a small config that is fine; for a large one the message is a wall of paths. - Compile time and limits. Every instantiation is work for the checker, and the editor repeats it on every keystroke. Deep recursion stops with "Type instantiation is excessively deep and possibly infinite."
tsc --extendedDiagnosticsprints the instantiation count and check time, andtsc --generateTrace <dir>writes a trace that shows which types are slow. - False confidence. A computed type describes what the runtime code should do; the link between them is often a cast such as
return out as Getters<T>, and nothing checks it. A mistake in the implementation stays invisible behind a precise-looking type.
What to do instead
- Ask which bug the type prevents. If a hand-written union of five routes, a plain
stringplus one run-time check, or a named object type catches the same mistakes, prefer it. - Keep advanced types in one place, usually a shared module or a library boundary, and let application code use them by name.
- Name the intermediate steps (
type Keys = …,type Mapped = …) instead of nesting everything in one expression, and leave a comment with an example of the input and the output. - Test the types: calls that must compile and calls marked
// @ts-expect-errorthat must not, checked bytscin CI. Test the run-time code behind a cast as well.
A line that works for many teams, and it is a judgement call rather than a rule of the language: precise types at the edges, where they catch real mistakes, and simple types in the middle, where people read and change code every day.
Interview tips
30 saniyəlik cavab. "TypeScript tipləri başqa tiplərdən hesablaya bilir. typeof, keyof və indexed access tipləri dəyərlərdən və bir-birindən törədir. Partial, Pick, Omit, Record və ReturnType kimi utility tiplər standart kitabxanadakı generic tiplərdir, əksəriyyəti mapped tiplərdir: açarlar üzrə dövr edir, readonly və ? əlavə edə və ya silə, as ilə açarların adını dəyişə bilirlər. Conditional tiplər T extends U ? X : Y ilə tip seçir, infer uyğunluqdan tipləri çıxarır, union üzərində isə parametri tuple-a sarmasan, üzv-üzv paylanır. Mən onları bir həqiqət mənbəyi saxlamaq üçün işlədirəm və komandanın oxuya biləcəyi qədər sadə saxlayıram."
Gözlənilən suallar
Partial,Readonly,Pickvə yaRecord-u reallaşdır.keyof T(və yaK) üzrə düzgün modifikatorlu mapped tip;Pick-əK extends keyof Tlazımdır.ReturnType,Parametersvə yaElementTypereallaşdır. Uyğun mövqedəinferolan conditional tip.PickiləOmit-in fərqi nədir? "Saxla və ya sil"-dən əlavə:Omitaçarlarını yoxlamır və hər ikisi union-ları düzləşdirir.IsString<string | number>nə verir və niyə? Hər iki budağı, çünki conditional tip paylanır;[T] extends [string]union-ı bütöv yoxlayır.- Dəyərlər massivindən union tipi necə alırsan?
as constüstəgəl(typeof ARR)[number]. Awaitednə üçündür? Promise-in dəyər tipi, rekursiv açılmış; async funksiya üçün adətənAwaited<ReturnType<typeof fn>>.
Bal itirdən səhvlər
Readonly<T>-ni dəyişməzlik saymaq: o dayazdır və icra zamanı heç bir təsiri yoxdur.- Discriminated union-a
Omittətbiq edib variant sahələrinin hara getdiyinə təəccüblənmək. as const-u unudub törədilmiş tipin niyəstringolduğuna təəccüblənmək.- Əllə yazılmış beş üzvlü union-ın kifayət etdiyi yerdə dərin rekursiv tip yazmaq.
never-innever-ə paylandığını bilməmək.
Senior səviyyəni göstərən məqamlar
Trade-off-lardan danış. Tipləri köçürmək yox, törətdiyini göstər, eyni zamanda törətmənin nə vaxt həddən artıq bağlılıq yaratdığını da bildiyini: export olunan API adlı, açıq yazılmış tipə layiqdir. Ağıllı tiplərin qiymətini (oxunmayan xətalar, tip yoxlayıcısının vaxtı, tipi icra zamanına bağlayan cast) və onları necə məhdudlaşdıracağını qeyd et: bir modul, adlı aralıq tiplər, CI-da tip testləri. DistributiveOmit yaza bilirsənsə, ona niyə T extends unknown lazım olduğunu bir cümlə ilə izah et.
A 30-second answer. "TypeScript can compute types from other types. typeof, keyof and indexed access derive types from values and from each other. Utility types like Partial, Pick, Omit, Record and ReturnType are generic types in the standard library, mostly mapped types: they iterate over keys and can add or remove readonly and ?, or rename keys with as. Conditional types choose a type with T extends U ? X : Y, infer pulls types out of a match, and over a union they distribute member by member unless you wrap the parameter in a tuple. I use them to keep one source of truth, and I keep them simple enough for the team to read."
Questions you are likely to get
- Implement
Partial,Readonly,PickorRecord. A mapped type overkeyof T(orK) with the right modifier;PickneedsK extends keyof T. - Implement
ReturnType,Parametersor anElementType. A conditional type withinferin the matched position. - What is the difference between
PickandOmit? Beyond "keep vs remove":Omitdoes not check its keys, and both flatten unions. - What does
IsString<string | number>give, and why? Both branches, because the conditional type distributes;[T] extends [string]checks the union as a whole. - How do you get a union type from an array of values?
as constplus(typeof ARR)[number]. - What is
Awaitedfor? The value type of a promise, unwrapped recursively, typicallyAwaited<ReturnType<typeof fn>>for an async function.
Mistakes that cost points
- Treating
Readonly<T>as immutability: it is shallow and has no run-time effect. - Using
Omiton a discriminated union and wondering where the variant fields went. - Forgetting
as const, then wondering why the derived type isstring. - Writing a deeply recursive type where a hand-written union of five members would do.
- Not knowing that
neverdistributes tonever.
Senior signal
Talk about trade-offs. Show that you derive types instead of copying them, and that you also know when deriving couples too much: an exported API deserves a named, explicit type. Mention the costs of clever types (unreadable errors, checker time, the cast that links the type to the runtime) and how you would contain them: one module, named intermediate types, type tests in CI. If you can write DistributiveOmit, explain in one sentence why it needs T extends unknown.
What to check when reviewing type transformations
Özün yazmadığın tipləri review edəndə bu siyahıdan istifadə et: komanda yoldaşının pull request-i, kitabxananın nümunəsi, AI assistentin təklifi. Törədilmiş və hesablanmış tiplər səssizcə sınır; qiyməti sonra ortaya çıxır: artıq dataya uyğun gəlməyən tip və ya heç kimin oxuya bilmədiyi xəta mesajı kimi.
- Tip mənbəyindən törədilib, yoxsa ondan köçürülüb? API tipinin, funksiyanın qaytardığı dəyərin və ya icazə verilən dəyərlər siyahısının əllə yazılmış surəti orijinal dəyişən kimi ondan ayrı düşür. İkinci tərif görünən yerdə
typeof,keyof,ReturnTypevəas constmassivləri axtar. Omit-ə ötürülən açarlar mövcuddurmu?Omitistənilən sətri qəbul edir, ona görə yazı səhvi və ya adı dəyişdirilmiş sahə heç nəyi silmir. Redaktorda nəticənin üzərinə hover et, ya da naməlum açarları rədd edənPickvə ya açarları yoxlayanOmitişlət.Omitvə yaPickunion-a tətbiq olunub? Onlar yalnız bütün üzvlərin ortaq açarlarını saxlayır, ona görə discriminated union variant sahələri olmayan tək obyektə çevrilir. Nəticənin üzərinə hover et; union qalmalıdırsa, distributive versiyanı işlət.Readonlyvə yaPartialverdiyindən çoxunu vəd edir?Readonlydayazdır və icra zamanı heç nə etmir;Partialçağıranlara açıq şəkildəundefinedötürməyə imkan verir. İç-içə massiv və obyektləri, partial obyektin spread-inin məcburi sahələrə nə etdiyini yoxla.- Hesablanmış tip icra zamanı koda cast ilə bağlanıb? Açarları yenidən adlandırılan mapped tiplər və conditional qaytarma tipləri çox vaxt
as SomeTypeilə bitir. İmplementasiyanı tiplə yanaşı oxu və ya işə sal, yaradılan açar və dəyərlərin həqiqətən uyğun gəldiyini yoxla. - Conditional tip paylanmamalı olduğu yerdə paylanır, yoxsa əksinə? Qısa tip testində ona union və
neverver:IsStringkimi "sual" tipinə adətən[T] extends [U]lazımdır. - Komanda yoldaşı tipi və onun yaratdığı xətaları oxuya bilirmi? Çağırış yerində qəsdən səhv et və mesajı oxu. O, generasiya olunmuş üzvlərdən ibarət divardırsa və ya
tsc --extendedDiagnosticsinstantiation sayının sıçradığını göstərirsə, sadələşdir və ya addımlara ad ver.
Use this list when you review types you did not write: a teammate's pull request, a library's example, an AI assistant's suggestion. Derived and computed types fail quietly; the cost shows up later, as a type that no longer matches the data or an error message nobody can read.
- Is the type derived from its source, or copied from it? A hand-written copy of an API type, a function's return value or a list of allowed values drifts as soon as the original changes. Look for
typeof,keyof,ReturnTypeandas constarrays where a second definition appears. - Do the keys passed to
Omitexist?Omitaccepts any string, so a typo or a renamed field removes nothing. Hover the result in the editor, or usePickor a key-checkedOmit, which reject unknown keys. - Is
OmitorPickapplied to a union? They keep only the keys all members share, so a discriminated union collapses into one object without its variant fields. Hover the result; use a distributive version when it should stay a union. - Does
ReadonlyorPartialpromise more than it delivers?Readonlyis shallow and does nothing at run time;Partiallets callers passundefinedexplicitly. Check nested arrays and objects, and what a spread of a partial object does to required fields. - Is a computed type connected to the runtime code by a cast? Mapped types with renamed keys and conditional return types often end in
as SomeType. Read the implementation next to the type, or run it, and check that the produced keys and values really match. - Does a conditional type distribute when it should not, or the other way round? Feed it a union and
neverin a quick type test: a "question" type likeIsStringusually needs[T] extends [U]. - Can a teammate read the type and the errors it produces? Make a deliberate mistake at a call site and read the message. If it is a wall of generated members, or
tsc --extendedDiagnosticsshows the instantiation count jumping, simplify or name the steps.