Generic-lər
Generic-lər funksiyaya və ya tipə daxil olan tiplərlə ondan çıxan tiplər arasındakı əlaqəni necə saxlayır: tip parametrləri və çağırış yerində tipin çıxarılması, məhdudiyyətlər, keyof və indexed access, default-lar, generic klasslar, lazımsız tip parametrləri, const tip parametrləri, NoInfer və variance.
Oxu səviyyəsi
Seçilmiş səviyyəyə qədər olan bölmələr göstərilir.
Başlamazdan əvvəl
Bu mövzu Junior səviyyəsindən başlayır.
Generic-lər nə üçündür
Çox tiplə işləyən funksiya da nə qaytardığını deməlidir. Massivin ilk elementini qaytaran köməkçi funksiyanı götürək. any ilə o, istənilən massivi qəbul edir, amma içəri girənlə çölə çıxan arasındakı əlaqə itir:
function firstAny(items: any[]): any {
return items[0];
}
const id = firstAny(["a1", "b2"]); // id: any
id.toFixed(2); // compile olunur, icra zamanı TypeError atırany əvəzinə unknown təhlükəsizdir, amma onda hər çağıran tipini onsuz da bildiyi dəyəri ilə daraltmalı olur. Hər tip üçün ayrıca funksiya yazmaq (firstString, firstNumber) da miqyaslanmır.
bunu tip parametri ilə həll edir: bucaqlı mötərizələrdə yazılan və hər çağırışda doldurulan tip yer tutucusu.
function first<T>(items: T[]): T | undefined {
return items[0];
}
const a = first(["a1", "b2"]); // a: string | undefined
const n = first([1, 2, 3]); // n: number | undefined
a?.toUpperCase(); // OK
n?.toUpperCase(); // Error: Property 'toUpperCase' does not exist on type 'number'.İmzanı cümlə kimi oxu: "istənilən T tipi üçün mənə T massivi ver, mən T qaytarım, massiv boşdursa undefined". Funksiya artıq konkret bir tip vəd etmir; arqumentlə nəticə arasında əlaqə vəd edir. any-nin atıb itirdiyi də məhz bu əlaqədir.
| undefined dürüst yazılıb. noUncheckedIndexedAccess açıq deyilsə, items[0] T tipində sayılır, yəni kompilyator qaytarılan tip kimi : T-ni də qəbul edərdi, funksiya isə [] üçün yenə undefined qaytarardı.
Artıq istifadə etdiyin generic-lər
Çoxlu daxili tip generic-dir. string[] Array<string>-in qısa yazılışıdır, fetch() Promise<Response> qaytarır, Map<K, V> və Set<T> isə açar və dəyər tiplərini parametr kimi alır.
Tip parametri nə deyil
T yalnız tip yoxlayıcısı üçün mövcuddur. Hər tip kimi o da kod kompilyasiya olunanda , ona görə funksiyanın gövdəsi T-nin nə olduğunu soruşa bilməz: typeof T yoxdur, first<number> və first<string> isə tam eyni JavaScript-i icra edir. Generic funksiya qəbul etdiyi hər tip üçün işləməlidir.
Qısa imzalarda tək hərf adlar qəbul olunub: tip üçün T, açar üçün K, dəyər üçün V. Uzun imzada isə TItem və ya Item kimi ad daha yaxşı oxunur.
A function that works with many types still has to say what it returns. Take a helper that returns the first element of an array. With any it accepts every array, but the link between what goes in and what comes out is lost:
function firstAny(items: any[]): any {
return items[0];
}
const id = firstAny(["a1", "b2"]); // id: any
id.toFixed(2); // compiles, throws a TypeError at run timeunknown instead of any is safe, but then every caller has to a value whose type it already knows. One function per type (firstString, firstNumber) does not scale either.
solve this with a type parameter: a placeholder for a type, written in angle brackets, that is filled in at each call.
function first<T>(items: T[]): T | undefined {
return items[0];
}
const a = first(["a1", "b2"]); // a: string | undefined
const n = first([1, 2, 3]); // n: number | undefined
a?.toUpperCase(); // OK
n?.toUpperCase(); // Error: Property 'toUpperCase' does not exist on type 'number'.Read the signature as a sentence: "for any type T, give me an array of T and I return a T, or undefined for an empty array". The function no longer promises one specific type; it promises a relation between the argument and the result. That relation is exactly what any throws away.
The | undefined is honest. Unless noUncheckedIndexedAccess is on, items[0] is typed as T, so the compiler would also accept : T as the return type, and the function would still return undefined for [].
Generics you already use
Many built-in types are generic. string[] is shorthand for Array<string>, fetch() returns Promise<Response>, and Map<K, V> and Set<T> take their key and value types.
What a type parameter is not
T exists only for the type checker. Like every type, it is when the code is compiled, so the body cannot ask what T is: there is no typeof T, and first<number> and first<string> run exactly the same JavaScript. A generic function has to work for every type it accepts.
Single letters are the convention for short signatures: T for a type, K for a key, V for a value. In a longer signature, a name such as TItem or Item reads better.
Tip arqumentləri və tipin çıxarılması
Tip arqumentini özün ötürə bilərsən, ya da qoy TypeScript onu özü müəyyən etsin:
first<string>(["a", "b"]); // açıq yazılıb
first(["a", "b"]); // çıxarılıb: T string-dirTip arqumentinin çağırışdan müəyyən edilməsi , yəni tipin çıxarılmasıdır. TypeScript hər arqumenti parametrinin tipi ilə tutuşdurur: ["a", "b"] string[]-dir, parametr T[]-dir, deməli T string-dir. Çıxarılmaya üstünlük ver; tip arqumentini yalnız çıxarmaq üçün heç nə olmayanda və ya TypeScript nəzərdə tutmadığın tipi seçəndə yaz.
Çıxarılma callback-lərə də keçir
Bir neçə tip parametri olanda çıxarılma arqumentlər üzrə irəliləyir:
function map<T, U>(items: T[], fn: (item: T) => U): U[] {
return items.map(fn);
}
const lengths = map(["a", "bb"], (s) => s.length); // number[]T massivdən gəlir, ona görə callback-in s parametri annotasiyasız da string olur (callback kontekstə görə tiplənir), U isə callback-in qaytardığından gəlir.
Çıxarılma başqa tip seçəndə
function combine<T>(a: T[], b: T[]): T[] {
return a.concat(b);
}
combine([1, 2], ["x"]); // Error: Type 'string' is not assignable to type 'number'.
combine<string | number>([1, 2], ["x"]); // OK: nə istədiyini açıq dedinT birinci massivdən number kimi çıxarılır, ikinci massiv isə sonra number[] ilə yoxlanır. Tipləri qarışdırmaq həqiqətən niyyətindirsə, bunu açıq tip arqumenti ilə bildir.
Çıxarmaq üçün heç nə olmayanda
const byId = new Map(); // Map<any, any>: içində saxlanan heç nə yoxlanmır
const tags = new Set(); // Set<unknown>
const users = new Map<string, User>(); // içinə nə qoyulacağını deBoş kolleksiya çıxarılmaya heç bir namizəd vermir, ona görə tip any-yə və ya unknown-a düşür. Tip arqumentlərini kolleksiyanı yaradanda ötür.
Bilməyə dəyən iki detal
- Açıq tip arqumentləri ya hamısı, ya heç biri prinsipi ilə işləyir:
map<string>(…)"Expected 2 type arguments, but got 1." xətası verir, çatışmayanların default-u yoxdursa. - Literal tiplər harada işləndiyindən asılı olaraq ya saxlanır, ya genişlənir.
const x = identity("hi")(identity<T>(value: T): Tilə)"hi"verir,let x = identity("hi")stringverir,first(["a", "b"])isə"a" | "b" | undefinedyox,string | undefinedverir.
You can pass the type argument yourself, or let TypeScript work it out:
first<string>(["a", "b"]); // explicit
first(["a", "b"]); // inferred: T is stringWorking out the type argument from the call is . TypeScript matches each argument against its parameter type: ["a", "b"] is a string[], the parameter is T[], so T is string. Prefer inference, and write a type argument only when inference has nothing to work with or picks a type you did not mean.
Inference flows into callbacks
With several type parameters, inference works through the arguments:
function map<T, U>(items: T[], fn: (item: T) => U): U[] {
return items.map(fn);
}
const lengths = map(["a", "bb"], (s) => s.length); // number[]T comes from the array, so the callback's s is already a string without an annotation (the callback is contextually typed), and U comes from what the callback returns.
When inference picks something else
function combine<T>(a: T[], b: T[]): T[] {
return a.concat(b);
}
combine([1, 2], ["x"]); // Error: Type 'string' is not assignable to type 'number'.
combine<string | number>([1, 2], ["x"]); // OK: you said what you meantT is inferred from the first array as number, and the second array is then checked against number[]. If mixing is intended, say so with an explicit type argument.
When there is nothing to infer from
const byId = new Map(); // Map<any, any>: nothing stored in it is checked
const tags = new Set(); // Set<unknown>
const users = new Map<string, User>(); // say what goes inAn empty collection gives inference no candidates, so the type falls back to any or unknown. Pass the type arguments when you create it.
Two details worth knowing
- Explicit type arguments are all or nothing:
map<string>(…)fails with "Expected 2 type arguments, but got 1." unless the missing ones have defaults. - Literal types are kept or widened depending on where they end up.
const x = identity("hi")(withidentity<T>(value: T): T) gives"hi",let x = identity("hi")givesstring, andfirst(["a", "b"])givesstring | undefined, not"a" | "b" | undefined.
extends ilə məhdudiyyətlər
Generic funksiyanın içində T istənilən tip ola bilər, ona görə T ilə yalnız hər tip üçün keçərli olanı edə bilərsən:
function longest<T>(a: T, b: T): T {
return a.length >= b.length ? a : b; // Error: Property 'length' does not exist on type 'T'.
}Məhdudiyyət (constraint) T-nin hansı tipləri qəbul etdiyini daraldır, əvəzində funksiyanın gövdəsinə nəyə arxalana biləcəyini deyir:
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
longest("apple", "fig"); // OK: sətirlərin length-i var
longest([1, 2], [3]); // OK: T number[]-dir
longest(10, 20); // Error: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.Burada extends klass irsiyyəti yox, "mənimsədilə bilir" (assignable) deməkdir. İstənilən tip məhdudiyyət ola bilər: T extends string, T extends object, T extends readonly unknown[], T extends (...args: never[]) => unknown.
Niyə parametri sadəcə məhdudiyyət tipi ilə yazmayaq?
function longestLoose(a: { length: number }, b: { length: number }) {
return a.length >= b.length ? a : b;
}
longestLoose("apple", "fig").toUpperCase(); // Error: Property 'toUpperCase' does not exist on type '{ length: number; }'.
longest("apple", "fig").toUpperCase(); // OKTip parametri olmayan versiya eyni arqumentləri qəbul edir, amma { length: number } qaytarır: çağıran sətir ötürüb, geri isə artıq sətir olmayan nəsə alır. Məhdudiyyət T-də nə olmalı olduğunu deyir, tip parametri isə onda olan qalan hər şeyi saxlayır.
Klassik səhv: yalnız məhdudiyyətə uyğun gələni qaytarmaq
function minimumLength<T extends { length: number }>(obj: T, minimum: number): T {
if (obj.length >= minimum) return obj;
return { length: minimum }; // Error
}Xəta belədir: "'{ length: number; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{ length: number; }'." İmza length-i olan istənilən obyekti yox, içəri girən tipin özünü qaytarmağı vəd edir. number[] ötürən çağıran geri number[] kimi tiplənmiş { length: 6 } alardı və .slice() çağıranda proqram çökərdi. TypeScript handbook-u məhz bu nümunəni göstərir.
Düzəliş ya həqiqi T qaytarmaq, ya da qaytarılan tipi { length: number } etməkdir. as T əlavə etmək xətanı yox edir, çöküşü isə yerində saxlayır.
Inside a generic function T can be any type, so you can only do with a T what works for every type:
function longest<T>(a: T, b: T): T {
return a.length >= b.length ? a : b; // Error: Property 'length' does not exist on type 'T'.
}A constraint limits which types T accepts and, in return, tells the body what it can rely on:
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
longest("apple", "fig"); // OK: strings have a length
longest([1, 2], [3]); // OK: T is number[]
longest(10, 20); // Error: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.extends here means "is assignable to", not class inheritance. Any type can be a constraint: T extends string, T extends object, T extends readonly unknown[], T extends (...args: never[]) => unknown.
Why not annotate with the constraint?
function longestLoose(a: { length: number }, b: { length: number }) {
return a.length >= b.length ? a : b;
}
longestLoose("apple", "fig").toUpperCase(); // Error: Property 'toUpperCase' does not exist on type '{ length: number; }'.
longest("apple", "fig").toUpperCase(); // OKThe version without a type parameter accepts the same arguments but returns { length: number }: the caller passed strings and gets back something that is no longer a string. The constraint says what T must have; the type parameter keeps everything else it has.
The classic mistake: returning something that only fits the constraint
function minimumLength<T extends { length: number }>(obj: T, minimum: number): T {
if (obj.length >= minimum) return obj;
return { length: minimum }; // Error
}The error reads: "'{ length: number; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{ length: number; }'." The signature promises to return the same type that came in, not just any object with a length. A caller that passes number[] would get { length: 6 } back, typed as number[], and crash on .slice(). The TypeScript handbook uses this exact example.
The fix is to return a real T or to change the return type to { length: number }. Adding as T makes the error go away and leaves the crash in place.
Generic funksiyalarda keyof və indexed access
İki tip operatoru generic-ləri obyektlər üçün faydalı edir: keyof T T-nin xassə adlarının union-ıdır, T[K] isə, yəni indexed access tipi, K xassəsinin tipidir. Bir tip parametrini digərinə bağlayan məhdudiyyətlə birlikdə onlar tip baxımından təhlükəsiz xassə oxuyan funksiya verir. TypeScript handbook-unun nümunəsi budur:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 7, name: "Aysel", email: null as string | null };
getProperty(user, "id"); // number
getProperty(user, "email"); // string | null
getProperty(user, "phone"); // Error: Argument of type '"phone"' is not assignable to parameter of type '"id" | "name" | "email"'.K extends keyof T "K T-nin açarlarından biridir" deməkdir. Çağırış zamanı T user-dən, K isə ötürdüyün sətirdən "id" literal tipi kimi çıxarılır, ona görə qaytarılan T[K] tipi number olur.
Niyə iki tip parametri
function getLoose<T>(obj: T, key: keyof T) {
return obj[key];
}
getLoose(user, "id"); // string | number | nullkey: keyof T olanda funksiya hansı açarın ötürüldüyünü artıq bilmir, ona görə nəticə T[keyof T] olur: bütün xassə tiplərinin union-ı. Əlavə K məhz konkret açarı yadda saxlamaq üçündür. Eyni şablon setter-i də tipləyir, burada dəyər açara uyğun gəlməlidir:
function setProperty<T, K extends keyof T>(obj: T, key: K, value: T[K]): void {
obj[key] = value;
}
setProperty(user, "id", "7"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.Eyni yolla T[K][] qaytaran pluck(items, key), açara görə sıralayan və ya qruplaşdıran köməkçilər, setValue("email", value) çağırışında dəyəri sahəyə görə yoxlayan form kitabxanaları tiplənir.
Açarlar haqqında bilməli olduğun iki şey
Object.keys(obj)(keyof T)[]yox,string[]qaytarır. TypeScript-də tipləmə , ona görə obyektin tipində sadalanandan çox xassəsi ola bilər və TypeScript hər açarınkeyof Tolduğuna zəmanət vermir. Belə açarlaobj-yə müraciətstrictrejimində xəta verir: "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type …". Gözlədiyin açarların tiplənmiş siyahısı üzərində dövr et, artıq açar ola bilməyəcəyini bildiyin yerdə isə bir dəfə assertion yaz (as (keyof T)[]) və səbəbini şərhdə izah et.- Index signature-un
keyof-unanumberda daxildir.{ [key: string]: number }üçünkeyofstring | number-dir, çünki JavaScript rəqəmli xassə açarlarını sətirə çevirir.
Two type operators make generics useful for objects: keyof T is the union of T's property names, and T[K], an indexed access type, is the type of property K. With a constraint that ties one type parameter to another, they give a type-safe property getter, the example the TypeScript handbook uses:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 7, name: "Aysel", email: null as string | null };
getProperty(user, "id"); // number
getProperty(user, "email"); // string | null
getProperty(user, "phone"); // Error: Argument of type '"phone"' is not assignable to parameter of type '"id" | "name" | "email"'.K extends keyof T means "K is one of T's keys". At the call, T is inferred from user and K from the string you pass, as the literal type "id", so the return type T[K] becomes number.
Why two type parameters
function getLoose<T>(obj: T, key: keyof T) {
return obj[key];
}
getLoose(user, "id"); // string | number | nullWith key: keyof T, the function no longer knows which key was passed, so the result is T[keyof T]: the union of every property's type. The extra K exists to remember the specific key. The same pattern types a setter, where the value must match the key:
function setProperty<T, K extends keyof T>(obj: T, key: K, value: T[K]): void {
obj[key] = value;
}
setProperty(user, "id", "7"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.It also types helpers such as pluck(items, key) returning T[K][], sorting or grouping by a key, and form libraries where setValue("email", value) checks the value against the field.
Two things to know about keys
Object.keys(obj)returnsstring[], not(keyof T)[]. Typing is , so an object can have more properties than its type lists, and TypeScript will not promise that every key is akeyof T. Indexingobjwith such a key fails understrict: "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type …". Iterate over a typed list of the keys you expect, or, where you know no extra keys can appear, assert once (as (keyof T)[]) and say why in a comment.keyofof an index signature includesnumber. For{ [key: string]: number },keyofisstring | number, because JavaScript turns numeric property keys into strings.
Generic interface-lər, klasslar və default-lar
Tip parametrləri interface-lərə, type alias-lara və klasslara da yazılır. Generic tip şablondur: harada işlədilirsə, orada tip arqumentləri lazımdır.
interface ApiResponse<T> {
data: T;
status: number;
}
type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };
const response: ApiResponse<User[]> = { data: [], status: 200 };
const parsed: Result<number> = { ok: false, error: new Error("Not a number") };
let broken: ApiResponse; // Error: Generic type 'ApiResponse<T>' requires 1 type argument(s).Default tip parametrləri
E = Error default-dur: onu yazmasan, Result<number> Result<number, Error> deməkdir. Handbook-un sadaladığı qaydalar, qısaca:
- default-u olan tip parametri məcburi deyil, məcburi parametrlər isə ondan sonra gələ bilməz:
<T = string, U>"Required type parameters may not follow optional type parameters." xətası verir; - default məhdudiyyəti ödəməlidir:
<T extends string = number>xətadır; - tip arqumentlərini ötürəndə yalnız məcburi olanları yazmaq kifayətdir;
- çağırışda çıxarılma heç bir namizəd tapmayanda
unknownəvəzinə default işlədilir.
Generic klasslar
class Cache<K, V> {
#items = new Map<K, V>();
get(key: K): V | undefined {
return this.#items.get(key);
}
set(key: K, value: V): this {
this.#items.set(key, value);
return this;
}
}
const prices = new Cache<string, number>();
prices.set("apple", 1.2);
prices.set("pear", "cheap"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.Klassın tip parametrləri onun instance-larına aiddir: hər new Cache<…>() həmin obyekt üçün K və V-ni təyin edir. Static üzvləri bütün instance-lar bölüşür, ona görə onlar bu parametrlərdən istifadə edə bilməz: static empty: V "Static members cannot reference class type parameters." xətası verir. Tip arqumenti olmayanda və çıxarmaq üçün heç nə olmayanda new Cache() Cache<unknown, unknown> olur.
Klassa, yoxsa metoda?
Bütün metodlar tip parametrini bölüşürsə, onu klassa yaz, qiymətlər keşində olduğu kimi. Hər çağırış müstəqildirsə, metoda yaz:
class Logger {
tap<T>(value: T): T {
console.log(value);
return value;
}
}
const order = new Logger().tap({ id: 1 }); // { id: number }Logger<T> səbəbsiz yerə hər tip üçün ayrıca logger yaratmağa məcbur edərdi.
Type parameters also go on interfaces, type aliases and classes. A generic type is a template: wherever it is used, it needs its type arguments.
interface ApiResponse<T> {
data: T;
status: number;
}
type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };
const response: ApiResponse<User[]> = { data: [], status: 200 };
const parsed: Result<number> = { ok: false, error: new Error("Not a number") };
let broken: ApiResponse; // Error: Generic type 'ApiResponse<T>' requires 1 type argument(s).Default type parameters
E = Error is a default: leave it out, and Result<number> means Result<number, Error>. The rules the handbook lists, in short:
- a type parameter with a default is optional, and required ones may not follow it:
<T = string, U>fails with "Required type parameters may not follow optional type parameters."; - the default must satisfy the constraint:
<T extends string = number>is an error; - when you pass type arguments, you only have to pass the required ones;
- in a call, when inference finds no candidate, the default is used instead of
unknown.
Generic classes
class Cache<K, V> {
#items = new Map<K, V>();
get(key: K): V | undefined {
return this.#items.get(key);
}
set(key: K, value: V): this {
this.#items.set(key, value);
return this;
}
}
const prices = new Cache<string, number>();
prices.set("apple", 1.2);
prices.set("pear", "cheap"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.A class's type parameters belong to its instances: each new Cache<…>() fixes K and V for that object. Static members are shared by all instances, so they cannot use them: static empty: V fails with "Static members cannot reference class type parameters." With no type arguments and nothing to infer from, new Cache() is a Cache<unknown, unknown>.
On the class or on the method?
Put the type parameter on the class when every method shares it, as in a cache of prices. Put it on the method when each call stands alone:
class Logger {
tap<T>(value: T): T {
console.log(value);
return value;
}
}
const order = new Logger().tap({ id: 1 }); // { id: number }A Logger<T> would force one logger per type for no reason.
Generic nə vaxt lazım deyil
Tip parametri yerini iki şeyi bir-birinə bağlamaqla qazanır: arqumentlə nəticəni, iki arqumenti, açarla onun dəyərini. TypeScript handbook-u bunu qayda kimi deyir: tip parametri yalnız bir yerdə görünürsə, ona həqiqətən ehtiyac olub-olmadığını ciddi şəkildə yenidən düşün. Çıxarılan qaytarma tipi də yer sayılır.
Bir dəfə işlənib: sadəcə tipi yaz
function greet<S extends string>(name: S): void {
console.log("Hello, " + name);
}S heç nəyi bağlamır, greet(name: string) isə eyni şeyi daha sadə deyir. format<T extends string | number>(value: T): string də belədir: union tipli parametr işi görür.
Yalnız qaytarma tipində: maskalanmış yoxlanmayan cast
async function fetchJson<T>(url: string): Promise<T> {
const response = await fetch(url);
return response.json(); // any, T kimi qəbul olunur
}
const me = await fetchJson<User>("/api/me");T yalnız qaytarma tipində görünür, ona görə onu data ilə heç nə bağlamır. response.json() Promise<any> qaytarır, any istənilən T-yə mənimsədilə bilir və kompilyator çağıranın istədiyi hər tipi qəbul edir. Çağırış tiplənmiş API kimi görünür, amma əslində bir neçə əlavə addımla yazılmış (as User): server { "error": "expired" } cavabı versə, me.name undefined olur və bunu heç bir tip tutmur. parseJson<T>(text), storage.get<T>(key) və oxşar köməkçilərin də problemi eynidir.
Bunun əvəzinə unknown qaytar və sərhəddə yoxla, ya da validator-u parametr kimi al ki, tip parametri real nəyisə bağlasın:
async function fetchJson<T>(url: string, parse: (data: unknown) => T): Promise<T> {
const response = await fetch(url);
return parse(await response.json());
}
const me = await fetchJson("/api/me", parseUser); // T User-dir, parseUser-dən çıxarılıbİndi T parser-dən gəlir və data kimsə ondan istifadə etməzdən əvvəl yoxlanır.
Tip parametrlərini aşağı endir, sayını azalt
Handbook-dan daha iki tövsiyə:
function firstElement1<T>(arr: T[]) {
return arr[0]; // T qaytarır
}
function firstElement2<T extends any[]>(arr: T) {
return arr[0]; // any qaytarır
}firstElement2([1, 2, 3]) any qaytarır, çünki gövdə element tipini gözləmək əvəzinə any[] məhdudiyyətinin indeksinə müraciət edir. Tip parametri səni maraqlandıran şey olsun, burada bütöv arqument yox, element. Func extends (arg: T) => boolean kimi heç nəyi bağlamayan tip parametri isə tip arqumentlərini açıq yazan çağıranlara sadəcə bir arqument artıq yazdırır.
A type parameter earns its place by relating two things: an argument and the result, two arguments, a key and its value. The TypeScript handbook puts it as a rule: if a type parameter appears in only one place, strongly reconsider whether you need it. The inferred return type counts as a place.
Used once: just use the type
function greet<S extends string>(name: S): void {
console.log("Hello, " + name);
}S relates nothing, and greet(name: string) says the same thing more simply. The same goes for format<T extends string | number>(value: T): string: a union parameter type does the job.
Return type only: an unchecked cast in disguise
async function fetchJson<T>(url: string): Promise<T> {
const response = await fetch(url);
return response.json(); // any, accepted as T
}
const me = await fetchJson<User>("/api/me");T appears only in the return type, so nothing connects it to the data. response.json() returns Promise<any>, any is assignable to every T, and the compiler accepts whatever the caller asks for. The call looks like a typed API, but it is a , as User, with extra steps: if the server answers { "error": "expired" }, me.name is undefined and no type caught it. parseJson<T>(text), storage.get<T>(key) and similar helpers have the same problem.
Return unknown and validate at the boundary instead, or take the validator as a parameter so that the type parameter relates something real:
async function fetchJson<T>(url: string, parse: (data: unknown) => T): Promise<T> {
const response = await fetch(url);
return parse(await response.json());
}
const me = await fetchJson("/api/me", parseUser); // T is User, inferred from parseUserNow T comes from the parser, and the data is checked before anyone uses it.
Push type parameters down, use fewer of them
Two more guidelines from the handbook:
function firstElement1<T>(arr: T[]) {
return arr[0]; // returns T
}
function firstElement2<T extends any[]>(arr: T) {
return arr[0]; // returns any
}firstElement2([1, 2, 3]) returns any, because the body indexes the constraint any[] instead of waiting for the element type. Make the type parameter the thing you care about, here the element, not the whole argument. And a type parameter such as Func extends (arg: T) => boolean, which relates nothing, only makes callers who pass type arguments write one more.
Nümunə: tiplənmiş event emitter
Tiplənmiş event emitter indiyədək gördüyümüz hər şeyi birləşdirir: məhdudiyyət, keyof, indexed access, klassda və onun metodlarında tip parametrləri. Bir tip bütün event-ləri və onların payload-larını təsvir edir; on və emit səhv adları və səhv payload-ları rədd edir.
type AppEvents = {
login: { userId: string };
logout: undefined;
"cart:add": { productId: string; quantity: number };
};
type Handler<T> = (payload: T) => void;
class Emitter<Events extends Record<string, unknown>> {
#handlers: { [K in keyof Events]?: Set<Handler<Events[K]>> } = {};
on<K extends keyof Events>(type: K, handler: Handler<Events[K]>): () => void {
const handlers = (this.#handlers[type] ??= new Set());
handlers.add(handler);
return () => handlers.delete(handler);
}
emit<K extends keyof Events>(type: K, payload: Events[K]): void {
this.#handlers[type]?.forEach((handler) => handler(payload));
}
}Eventsemitter yaradılanda bir dəfə təyin olunur:new Emitter<AppEvents>().Khər çağırışda event adından çıxarılır, ona görəEvents[K]məhz həmin event-in payload-udur.#handlersmapped tipdir (onların ayrıca mövzusu var): hər event üçün məcburi olmayan bir handler Set-i, hər biri həmin event-in payload-una görə tiplənib, heç biranyolmadan.onabunəlikdən çıxma funksiyası qaytarır, ona görə çağıranlar handler-i yadda saxlamalı olmur.
const events = new Emitter<AppEvents>();
const off = events.on("cart:add", (item) => {
console.log(item.quantity); // item: { productId: string; quantity: number }
});
events.emit("login", { userId: "u1" });
events.emit("login", { id: "u1" }); // Error: Object literal may only specify known properties, and 'id' does not exist in type '{ userId: string; }'.
events.emit("signup", {}); // Error: Argument of type '"signup"' is not assignable to parameter of type 'keyof AppEvents'.
events.emit("logout"); // Error: Expected 2 arguments, but got 1.
off();Review edən nəyi soruşardı
- Məhdudiyyət interface-ləri rədd edir.
interface AppEvents { … }olsa,new Emitter<AppEvents>()"Index signature for type 'string' is missing in type 'AppEvents'" xətası verir: interface-lər gizli (implicit) index signature almır, type alias-lar isə alır.typeistifadə et, ya da hər ikisini qəbul edənEvents extends objectməhdudiyyətini yaz. - Payload-u olmayan event-lər üçün də
emit("logout", undefined)yazmaq lazımdır. İkinci arqumenti yalnız belə event-lər üçün məcburi olmayan etmək conditional tip tələb edir. - Tiplər payload-un haradan gəldiyi barədə heç nə demir. Kənardan gələn data (WebSocket mesajı,
postMessage) emit olunmazdan əvvəl yoxlanmalıdır; emitter onu sadəcə ötürür.
A typed event emitter combines everything so far: a constraint, keyof, indexed access, and type parameters on a class and on its methods. One type describes every event and its payload; on and emit reject wrong names and wrong payloads.
type AppEvents = {
login: { userId: string };
logout: undefined;
"cart:add": { productId: string; quantity: number };
};
type Handler<T> = (payload: T) => void;
class Emitter<Events extends Record<string, unknown>> {
#handlers: { [K in keyof Events]?: Set<Handler<Events[K]>> } = {};
on<K extends keyof Events>(type: K, handler: Handler<Events[K]>): () => void {
const handlers = (this.#handlers[type] ??= new Set());
handlers.add(handler);
return () => handlers.delete(handler);
}
emit<K extends keyof Events>(type: K, payload: Events[K]): void {
this.#handlers[type]?.forEach((handler) => handler(payload));
}
}Eventsis fixed once, when the emitter is created:new Emitter<AppEvents>().Kis inferred at each call from the event name, soEvents[K]is the payload of that event.#handlersis a mapped type (they get their own topic): one optional set of handlers per event, each typed for that event's payload, with noany.onreturns an unsubscribe function, so callers do not have to keep the handler around.
const events = new Emitter<AppEvents>();
const off = events.on("cart:add", (item) => {
console.log(item.quantity); // item: { productId: string; quantity: number }
});
events.emit("login", { userId: "u1" });
events.emit("login", { id: "u1" }); // Error: Object literal may only specify known properties, and 'id' does not exist in type '{ userId: string; }'.
events.emit("signup", {}); // Error: Argument of type '"signup"' is not assignable to parameter of type 'keyof AppEvents'.
events.emit("logout"); // Error: Expected 2 arguments, but got 1.
off();What a reviewer would ask about
- The constraint rejects interfaces. With
interface AppEvents { … },new Emitter<AppEvents>()fails with "Index signature for type 'string' is missing in type 'AppEvents'": interfaces do not get an implicit index signature, type aliases do. Use atype, or constrain withEvents extends object, which accepts both. - Events without a payload still need
emit("logout", undefined). Making the second argument optional only for those events takes a conditional type. - The types say nothing about where a payload came from. Data from outside (a WebSocket message,
postMessage) has to be validated before it is emitted; the emitter only passes it on.
const tip parametrləri və NoInfer
const tip parametrləri
Default olaraq çıxarılma massiv və obyektlərin içindəki literalları genişləndirir, çünki belə dəyərlər adətən sonradan dəyişir:
function createNavigator<T extends readonly string[]>(paths: T) {
return (path: T[number]) => location.assign(path);
}
const navigate = createNavigator(["/", "/about", "/pricing"]);
navigate("/abuot"); // xəta yoxdur: T string[]-dir, deməli T[number] string-dirKöhnə həll hər çağırandan as const istəmək idi. TypeScript 5.0-dan bəri funksiya bunu özü istəyə bilir, tip parametrinə const modifikatoru yazmaqla:
function createNavigator<const T extends readonly string[]>(paths: T) {
return (path: T[number]) => location.assign(path);
}
const navigate = createNavigator(["/", "/about", "/pricing"]);
// T readonly ["/", "/about", "/pricing"]-dir
navigate("/about"); // OK
navigate("/abuot"); // Error: Argument of type '"/abuot"' is not assignable to parameter of type '"/" | "/about" | "/pricing"'.T[number] number ilə indexed access-dir: tuple elementlərinin tiplərinin union-ı. Buraxılış qeydlərindən iki qayda:
constyalnız çağırışın içində yazılmış literallara təsir edir.const paths = ["/", "/about"]; createNavigator(paths)yenəstring[]verir, çünkipathselan olunanda artıq genişlənib.- Məhdudiyyəti buraxılış qeydlərinin tövsiyə etdiyi kimi
readonly string[]yaz:constçıxarılması readonly tuple-lar yaradır, readonly məhdudiyyət isə onları qəbul edir.
NoInfer
Tip parametri bir neçə parametrdə görünəndə onların hər biri çıxarılma üçün namizəddir. Bəzən parametrlərdən biri həqiqət mənbəyi olmalı, qalanları isə yalnız onunla yoxlanmalıdır:
function createStreetLight<C extends string>(colors: C[], defaultColor?: C) {}
createStreetLight(["red", "yellow", "green"], "blue"); // qəbul olunur: C "red" | "yellow" | "green" | "blue"-durTypeScript 5.4 NoInfer<T> utility tipini əlavə etdi. Parametrin tipini onunla bükmək həmin mövqeyi tip çıxarılmasından kənarlaşdırır; tipin özü isə C olaraq qalır:
function createStreetLight<C extends string>(colors: C[], defaultColor?: NoInfer<C>) {}
createStreetLight(["red", "yellow", "green"], "blue"); // Error: Argument of type '"blue"' is not assignable to parameter of type '"red" | "yellow" | "green" | undefined'.5.4-dən əvvəl çıxış yolu yalnız bir dəfə işlənən ikinci tip parametri, D extends C, idi.
Hər iki nümunədə literal tiplər yalnız C extends string sayəsində saxlanır: primitiv tipi ehtiva edən məhdudiyyət "red" kimi literal namizədləri saxlayır. Məhdudiyyətsiz C isə sadəcə string kimi çıxarılardı və "blue" NoInfer ilə də keçərdi.
const type parameters
By default, inference widens literals inside arrays and objects, because such values usually change later:
function createNavigator<T extends readonly string[]>(paths: T) {
return (path: T[number]) => location.assign(path);
}
const navigate = createNavigator(["/", "/about", "/pricing"]);
navigate("/abuot"); // no error: T is string[], so T[number] is stringThe old fix was to ask every caller for as const. Since TypeScript 5.0 the function can ask for it itself, with a const modifier on the type parameter:
function createNavigator<const T extends readonly string[]>(paths: T) {
return (path: T[number]) => location.assign(path);
}
const navigate = createNavigator(["/", "/about", "/pricing"]);
// T is readonly ["/", "/about", "/pricing"]
navigate("/about"); // OK
navigate("/abuot"); // Error: Argument of type '"/abuot"' is not assignable to parameter of type '"/" | "/about" | "/pricing"'.T[number] is an indexed access with number: the union of the tuple's element types. Two rules from the release notes:
constaffects only literals written in the call.const paths = ["/", "/about"]; createNavigator(paths)still givesstring[], becausepathswas widened when it was declared.- Write the constraint as
readonly string[], as the release notes recommend:constinference produces readonly tuples, and a readonly constraint accepts them.
NoInfer
When a type parameter appears in several parameters, each of them is an inference candidate. Sometimes one parameter should be the source of truth and the others should only be checked against it:
function createStreetLight<C extends string>(colors: C[], defaultColor?: C) {}
createStreetLight(["red", "yellow", "green"], "blue"); // accepted: C is "red" | "yellow" | "green" | "blue"TypeScript 5.4 added the NoInfer<T> utility type. Wrapping a parameter's type in it removes that position from inference; the type itself stays C:
function createStreetLight<C extends string>(colors: C[], defaultColor?: NoInfer<C>) {}
createStreetLight(["red", "yellow", "green"], "blue"); // Error: Argument of type '"blue"' is not assignable to parameter of type '"red" | "yellow" | "green" | undefined'.Before 5.4 the workaround was a second type parameter, D extends C, used only once.
Both examples keep literal types only because of C extends string: a constraint that includes a primitive type keeps literal candidates such as "red". An unconstrained C would be inferred as plain string, and "blue" would pass even with NoInfer.
Variance-a qısa baxış
Dog Animal-a mənimsədilə bilirsə, Box<Dog> Box<Animal>-a mənimsədilə bilərmi? Bu, Box-un öz tip parametri ilə nə etdiyindən asılıdır. Bu xüsusiyyət variance adlanır və TypeScript onu tipin strukturuna baxıb özü müəyyən edir:
type Animal = { name: string };
type Dog = Animal & { bark(): string };
interface Getter<T> { get: () => T } // T yalnız çölə çıxır
interface Setter<T> { set: (value: T) => void } // T yalnız içəri girir
declare const getDog: Getter<Dog>;
declare const setAnimal: Setter<Animal>;
declare const setDog: Setter<Dog>;
const g: Getter<Animal> = getDog; // OK: kovariant
const s1: Setter<Dog> = setAnimal; // OK: kontravariant
const s2: Setter<Animal> = setDog; // Error: Type 'Setter<Dog>' is not assignable to type 'Setter<Animal>'.- Kovariant (
Tçıxış mövqeyində): generic tipTilə eyni istiqamətdə gedir. It verən şey heyvan da verir. - Kontravariant (
Tgiriş mövqeyində): istiqamət çevrilir. İstənilən heyvanı qəbul edən şey iti də qəbul edir, amma it handler-inə pişik vermək olmaz. - İnvariant:
Thəm içəri girir, həm çölə çıxır, ona görə heç bir istiqamət təhlükəsiz deyil.
TypeScript-in qəsdən güzəştə getdiyi yerlər
Metod sintaksisi. strict-in tərkibində olan strictFunctionTypes parametrləri bu ciddiliklə yalnız funksiya sintaksisində yoxlayır. tsconfig reference-i deyir ki, metodlar kənarda saxlanılıb, çünki mövcud klass iyerarxiyalarının çoxu, DOM-dakıların bir qismi də daxil, pozulardı:
interface Formatter<T> { format(value: T): string } // metod sintaksisi
interface StrictFormatter<T> { format: (value: T) => string } // property sintaksisi
declare const upper: Formatter<string>;
declare const strictUpper: StrictFormatter<string>;
const loose: Formatter<string | number> = upper; // qəbul olunur: loose.format(42) çökə bilər
const checked: StrictFormatter<string | number> = strictUpper; // ErrorMassivlər. Massivlər dəyişkən olsa da, Dog[] Animal[]-a mənimsədilə bilir: push metoddur, ona görə onun parametri güzəştli qaydada müqayisə olunur. const animals: Animal[] = dogs; animals.push({ name: "Tom" }) kompilyasiya olunur və dogs-un içində bark-ı olmayan obyekt qoyur.
Bununla nə etməli
- Öz tiplərindəki callback-ləri property sintaksisi ilə elan et,
onChange: (value: T) => void, ki ciddi yoxlama işləsin. - Funksiya massivi yalnız oxuyursa,
readonly T[]qəbul etsin:readonly Animal[]parametriDog[]-u təhlükəsiz qəbul edir, çünki ona heç nə push etmək olmur. - Variance annotasiyaları TypeScript 4.7-dən var (
interface Producer<out T>,interface Consumer<in T>), amma handbook onları çox spesifik problemlər üçün qabaqcıl imkan adlandırır: onlar struktur yoxlamanı dəyişmir və yalnız strukturun onsuz da malik olduğu variance-ı ifadə etməlidir. Gündəlik kodda qoy TypeScript onu özü çıxarsın.
If Dog is assignable to Animal, is Box<Dog> assignable to Box<Animal>? It depends on what Box does with its type parameter. That property is called variance, and TypeScript works it out from the structure of the type:
type Animal = { name: string };
type Dog = Animal & { bark(): string };
interface Getter<T> { get: () => T } // T only comes out
interface Setter<T> { set: (value: T) => void } // T only goes in
declare const getDog: Getter<Dog>;
declare const setAnimal: Setter<Animal>;
declare const setDog: Setter<Dog>;
const g: Getter<Animal> = getDog; // OK: covariant
const s1: Setter<Dog> = setAnimal; // OK: contravariant
const s2: Setter<Animal> = setDog; // Error: Type 'Setter<Dog>' is not assignable to type 'Setter<Animal>'.- Covariant (
Tin output positions): the generic type follows the direction ofT. Something that produces dogs produces animals. - Contravariant (
Tin input positions): the direction flips. Something that accepts any animal also accepts a dog, but a dog handler cannot be given a cat. - Invariant:
Tgoes both in and out, so neither direction is safe.
Where TypeScript is deliberately loose
Method syntax. strictFunctionTypes, part of strict, checks parameters this strictly only in function syntax. The tsconfig reference says methods are left out because many existing class hierarchies, some in the DOM, would break:
interface Formatter<T> { format(value: T): string } // method syntax
interface StrictFormatter<T> { format: (value: T) => string } // property syntax
declare const upper: Formatter<string>;
declare const strictUpper: StrictFormatter<string>;
const loose: Formatter<string | number> = upper; // accepted: loose.format(42) can crash
const checked: StrictFormatter<string | number> = strictUpper; // ErrorArrays. Dog[] is assignable to Animal[] even though arrays are mutable: push is a method, so its parameter is compared the loose way. const animals: Animal[] = dogs; animals.push({ name: "Tom" }) compiles and leaves an object without bark inside dogs.
What to do with this
- Declare callbacks in your own types with property syntax,
onChange: (value: T) => void, to get the strict check. - Accept
readonly T[]when a function only reads: areadonly Animal[]parameter takes aDog[]safely, because nothing can be pushed into it. - Variance annotations exist since TypeScript 4.7 (
interface Producer<out T>,interface Consumer<in T>), but the handbook calls them an advanced feature for very specific problems: they do not change structural checks, and should only state the variance the structure already has. In everyday code, let TypeScript infer it.
Müsahibə üçün məsləhətlər
30 saniyəlik cavab. "Generic-lər funksiyaya və ya tipə tip parametrləri qəbul etməyə imkan verir: o, çox tiplə işləyir və onlar arasındakı əlaqəni saxlayır. first<T>(items: T[]): T | undefined aldığı istənilən massivin element tipini qaytarır, any isə bu tipi itirərdi. TypeScript tip arqumentlərini adətən çağırışdan özü çıxarır. T extends { length: number } kimi məhdudiyyət tipdə nə olmalı olduğunu deyir, K extends keyof T və T[K] isə açarı onun dəyərinin tipinə bağlayır. Yalnız bir dəfə görünən tip parametri şübhəli əlamətdir; yalnız qaytarma tipindədirsə, maskalanmış cast-dır."
Gözlənilən suallar
- Generic-lər,
anyvəunknownarasında fərq?anyyoxlamanı söndürür,unknownonu saxlayır, amma çağıranı narrowing etməyə məcbur edir, generic isə çağıranın öz tipini saxlayır. getProperty,pluckvə ya tiplənmiş event emitter yaz. İki tip parametri,K extends keyof T,T[K]qaytar; emitter üçün klassda event xəritəsi tipi və hər çağırışda çıxarılanK.minimumLengthniyə kompilyasiya olunmur? İmza çağıranın özT-sini vəd edir, yalnız məhdudiyyətə uyğun gələn dəyər isəTdeyil.- Tipin çıxarılması necə işləyir və tip arqumentlərini nə vaxt ötürürsən? Arqumentlərdən, oradan da callback-lərə; açıq şəkildə yalnız çıxarmaq üçün heç nə olmayanda (
new Map<string, User>()) və ya çıxarılan tip nəzərdə tutduğun tip olmayanda. consttip parametrləri vəNoInfernə edir? Çağırış yerindəas constolmadan literal çıxarılması (TypeScript 5.0); parametri tip çıxarılmasından kənarlaşdırmaq ki, o yalnız yoxlansın (TypeScript 5.4).- Variance nədir? Verənlər (producer) kovariant, qəbul edənlər (consumer) kontravariant, hər ikisini edən tiplər invariantdır; metod parametrləri və massivlər qəsdən güzəştli yerlərdir.
Bal itirdən səhvlər
<T>-ni yalnız bir dəfə göründüyü funksiyalara əlavə etmək.fetchJson<T>()və yaJSON.parse(text) as T-ni tip təhlükəsizliyi kimi təqdim etmək.- Generic xətasını imzanı düzəltmək əvəzinə
as Tvə yaas anyilə susdurmaq. - Məhdudiyyətdəki
extends-i klass irsiyyəti kimi başa düşmək. - Funksiyanın icra zamanı
T-yə görə budaqlana biləcəyini demək. Tiplər silinir; yalnız dəyərləri yoxlamaq olar.
Senior səviyyəni göstərən məqamlar
Çağıranlardan danış. Yaxşı generic API çıxarılmaya əsaslanır: çağıranlar tip arqumentlərini nadir hallarda yazır, xətalar isə tipin dərinliyini yox, səhv arqumenti göstərir. Generic-i nə vaxt ümumiyyətlə yazmayacağını de (bir konkret tip və ya sadə union), ortaq köməkçinin tiplərini necə test edəcəyini izah et: kompilyasiya olunmalı çağırışlar, üstəgəl // @ts-expect-error ilə işarələnmiş, kompilyasiya olunmamalı çağırışlar. Və zəmanətin harada bitdiyini de: sərhəddə generic yalnız arxasındakı yoxlama qədər doğrudur.
A 30-second answer. "Generics let a function or a type take type parameters, so it works with many types and keeps the relation between them: first<T>(items: T[]): T | undefined returns the element type of whatever array it gets, where any would lose it. TypeScript usually infers the type arguments from the call. A constraint like T extends { length: number } says what a type must have, and K extends keyof T with T[K] ties a key to its value type. A type parameter that appears only once is a smell; in the return type alone, it is a disguised cast."
Questions you are likely to get
- Generics vs
anyvsunknown?anyturns checking off,unknownkeeps it but makes the caller narrow, a generic keeps the caller's own type. - Write
getProperty,pluckor a typed event emitter. Two type parameters,K extends keyof T, returnT[K]; for the emitter, an event map type on the class andKinferred per call. - Why does
minimumLengthnot compile? The signature promises the caller's ownT, and a value that only matches the constraint is not aT. - How does inference work, and when do you pass type arguments? From the arguments, and from there into callbacks; explicitly only when there is nothing to infer from (
new Map<string, User>()) or the inferred type is not the one you mean. - What do
consttype parameters andNoInferdo? Literal inference withoutas constat the call site (TypeScript 5.0); excluding a parameter from inference so it is only checked (TypeScript 5.4). - What is variance? Producers are covariant, consumers contravariant, types that do both are invariant; method parameters and arrays are the deliberately loose spots.
Mistakes that cost points
- Adding
<T>to functions where it appears once. - Presenting
fetchJson<T>()orJSON.parse(text) as Tas type safety. - Silencing a generic error with
as Toras anyinstead of fixing the signature. - Reading
extendsin a constraint as class inheritance. - Suggesting the function can branch on
Tat run time. Types are erased; only values can be checked.
Senior signal
Talk about the callers. A good generic API is inferred, so callers rarely write type arguments, and its errors point at the wrong argument instead of deep inside a type. Say when you would not write a generic at all (one concrete type, or a plain union), and how you would test a shared helper's types: calls that must compile, plus calls marked // @ts-expect-error that must not. And say where the guarantee ends: at a boundary, a generic is only as true as the validation behind it.
Generic kodu review edərkən nəyi yoxlamalı
Yazmadığın generic kodu — komanda yoldaşının pull request-ini, kitabxananın nümunəsini, AI assistentin təklifini — review edəndə bu siyahıdan istifadə et. Səhv generic də kompilyasiya olunur; bunun qiyməti sonra üzə çıxır: çağıranlara sızan any kimi və ya heç kimin yoxlamadığı "tiplənmiş" nəticə kimi.
- Hər tip parametri imzada, qaytarma tipi də daxil olmaqla, ən azı iki dəfə görünürmü? Bir dəfə görünən parametr heç nəyi bağlamır: onu məhdudiyyəti və ya konkret tiplə əvəz et və bax, hansısa çağırış yeri tipini itirirmi.
- Tip parametri yalnız qaytarma tipində işlənibmi,
fetchJson<T>()və yaparse<T>(text)kimi? OndaT-ni çağıran seçir və datanı heç bir kod yoxlamır: bu, yoxlanmayan cast-dır.unknownnəticə və yoxlama, ya daT-nin çıxarıldığı validator parametri axtar. - Gövdənin kompilyasiya olunması üçün
as T,as anyvə ya@ts-ignorelazımdırmı? Adətən bu, imzanın gövdənin verə biləcəyindən çoxunu vəd etdiyini göstərir, çağıranın özT-sini vəd edən funksiyadan{ length: minimum }qaytarmaq kimi. Xətanı yox, imzanı və ya gövdəni düzəlt. - Funksiya məhdudiyyəti yox, tip parametrinin özünü qaytarırmı?
Ttipli arqument üçün{ length: number }qaytarma tipi çağıranın tipini atır. Redaktorda çağırışın üzərinə gəl: sətir arqumenti geri sətir verməlidir. - Açar parametrləri
K extends keyof T, dəyərlər isəT[K]ilə yazılıbmı? Cast ilə işlənənkey: stringvə ya bütün xassə tiplərinin union-ını qaytarankey: keyof Taçarla onun dəyəri arasındakı əlaqəni qırır. Çağırış yerində səhv yazılmış açar kompilyasiya olunmamalıdır. - Boş kolleksiyalara tip arqumentləri verilibmi?
new Map()Map<any, any>-dir, yəni içində saxlanan heç nə yoxlanmır. Diff-də tip arqumentsiznew Map()vənew Set()axtar. - Massivi yalnız oxuyan funksiyalar
readonly T[]qəbul edirmi, öz tiplərindəki callback-lər property sintaksisi ilə yazılıbmı? Massivlər və metod parametrləri güzəştli yoxlanır; bu iki vərdiş kompilyatora daha geniş tip vasitəsilə edilən yazmaları və az şey qəbul edən handler-ləri tutmağa imkan verir.
Use this list when you review generic code you did not write: a teammate's pull request, a library's example, an AI assistant's suggestion. A wrong generic still compiles; the cost shows up later, as any leaking into callers or a "typed" result that nothing ever checked.
- Does every type parameter appear at least twice in the signature, the return type included? One that appears once relates nothing: replace it with its constraint or a concrete type and see whether any call site loses a type.
- Is a type parameter used only in the return type, as in
fetchJson<T>()orparse<T>(text)? Then the caller picksTand no code checks the data: it is an unchecked cast. Look for anunknownresult plus validation, or a validator parameter from whichTis inferred. - Does the body need
as T,as anyor@ts-ignoreto compile? Usually the signature promises more than the body delivers, like returning{ length: minimum }from a function that promises the caller's ownT. Fix the signature or the body, not the error. - Does the function return the type parameter, not its constraint? A return type of
{ length: number }for an argument of typeTthrows away the caller's type. Hover a call in the editor: a string argument should give a string back. - Do key parameters use
K extends keyof T, and valuesT[K]? Akey: stringwith a cast, or akey: keyof Tthat returns the union of all property types, breaks the link between a key and its value. A misspelled key at a call site should not compile. - Are empty collections given type arguments?
new Map()isMap<any, any>, so nothing stored in it is checked. Search the diff fornew Map()andnew Set()without type arguments. - Do functions that only read an array take
readonly T[], and are callbacks in your own types written with property syntax? Arrays and method parameters are checked loosely; these two habits let the compiler catch writes through a wider type and handlers that accept too little.