Series: TypeScript Basics Lesson 59

Generic classes

TypeScript'da generic class'lar: konteyner class'lar, T'ni constructor'dan infer qilish, constraint, metod darajasidagi generic, static a'zolar cheklovi va bo'sh constructor'li class'ni type argumentsiz yaratish xatosi.

59-dars

Generic classes

Navbat, kesh, ombor kabi "konteyner" class'lar ichidagi ma'lumot type'iga bog'liq emas: ular elementlarni saqlaydi, qo'shadi, oladi. Misollarda quyidagi type'lardan foydalanamiz:

type Buyurtma = { id: number; summa: number };
type Foydalanuvchi = { id: number; ism: string };
type Mahsulot = { nomi: string; narx: number };
declare const mahsulot: Mahsulot;

Generic'siz ikki yomon yo'l qoladi:

// ❌ 1-yo'l: any — type xavfsizligi yo'q
class Navbat {
  elementlar: any[] = [];

  qosh(element: any) {
    this.elementlar.push(element);
  }

  ol(): any {
    return this.elementlar.shift();
  }
}

const buyurtmalar = new Navbat();
buyurtmalar.qosh("bu buyurtma emas"); // TS indamaydi
buyurtmalar.ol().summa.toFixed(2);    // TS indamaydi
// 💥 TypeError: Cannot read properties of undefined (reading 'toFixed')

// ❌ 2-yo'l: har bir type uchun alohida class
class BuyurtmaNavbati { /* ... */ }
class XabarNavbati    { /* ... */ } // xuddi o'sha kod, faqat type boshqa
// ✅ Yechim: generic class
class Navbat<T> {
  elementlar: T[] = [];

  qosh(element: T) {
    this.elementlar.push(element);
  }

  ol(): T | undefined {
    return this.elementlar.shift();
  }
}

const buyurtmalar = new Navbat<Buyurtma>();
buyurtmalar.qosh("bu buyurtma emas");
// ❌ Argument of type 'string' is not assignable to parameter of type 'Buyurtma'.

const keyingi = buyurtmalar.ol(); // Buyurtma | undefined
keyingi?.summa.toFixed(2);        // ✅

Bitta class, har bir nusxa (instance) uchun o'z type'i.

Qanday ishlaydi?

1. Asosiy sintaksis

Type parametr class nomidan keyin yoziladi va maydonlar, metod parametrlari, qaytish type'larida ishlatiladi:

class Quti<T> {
  qiymat: T;

  constructor(qiymat: T) {
    this.qiymat = qiymat;
  }

  yangila(yangi: T) {
    this.qiymat = yangi;
  }
}

2. T constructor'dan infer qilinadi

Interface va type alias'dan farqli o'laroq, class'da T constructor argumentidan aniqlanishi mumkin — funksiyalardagi kabi:

const narx = new Quti(85000);     // Quti<number>
const nom  = new Quti("Choynak"); // Quti<string>

narx.yangila("arzon");
// ❌ Argument of type 'string' is not assignable to parameter of type 'number'.

3. Constraint bilan

T extends { id: unknown } class'da ham ishlaydi:

class Kesh<T extends { id: number | string }> {
  saqlangan = new Map<T["id"], T>();

  qosh(element: T) {
    this.saqlangan.set(element.id, element); // ✅ id borligi kafolatlangan
  }

  top(id: T["id"]): T | undefined {
    return this.saqlangan.get(id);
  }
}

const fKesh = new Kesh<Foydalanuvchi>();
fKesh.top(5);     // ✅ id: number
fKesh.top("abc");
// ❌ Argument of type 'string' is not assignable to parameter of type 'number'.

4. Metod darajasidagi generic

Class'ning T'si nusxa uchun bitta, metodning o'z U'si esa har chaqiruvda yangi:

class Royxat<T> {
  elementlar: T[];

  constructor(elementlar: T[]) {
    this.elementlar = elementlar;
  }

  ozgartir<U>(f: (x: T) => U): Royxat<U> {
    return new Royxat(this.elementlar.map(f));
  }
}

const mahsulotlar = new Royxat([{ nomi: "Choynak", narx: 85000 }]);
const nomlar  = mahsulotlar.ozgartir((m) => m.nomi); // Royxat<string>
const narxlar = mahsulotlar.ozgartir((m) => m.narx); // Royxat<number>

5. static a'zolar T'ni ko'rmaydi

T har bir nusxa uchun belgilanadi, static a'zolar esa class'ning o'ziga tegishli — barcha nusxalar uchun bitta:

class Navbat<T> {
  static bosh: T[] = [];
  // ❌ Static members cannot reference class type parameters.
}

Eng ko'p uchraydigan xato

Bo'sh constructor'li generic class'ni type argumentsiz yaratish.

const navbat = new Navbat(); // Navbat<unknown>

navbat.qosh({ id: 1, summa: 50000 });
navbat.qosh("tasodifiy matn"); // 🐛 TS indamaydi — unknown hammasini qabul qiladi
navbat.qosh(42);

const keyingi = navbat.ol(); // unknown (unknown | undefined = unknown)
keyingi.summa;
// ❌ 'keyingi' is of type 'unknown'.

Standart class'larda bu yanada xavfli:

const kesh = new Map(); // Map<any, any> — unknown ham emas, any!
kesh.set(1, "matn");
kesh.get(1).summa.toFixed(); // TS indamaydi
// 💥 TypeError: Cannot read properties of undefined (reading 'toFixed')

Nega bunday bo'ladi? TS T'ni constructor argumentlaridan aniqlaydi. Argument yo'q bo'lsa, T uchun manba yo'q — natijada unknown (sizning class'ingizda) yoki any (ba'zi standart class'larda, masalan, Map) bo'ladi. Ikkala holatda ham generic class'ning butun foydasi yo'qoladi: kirishda hech narsa tekshirilmaydi.

✅ Yechim 1: type argumentni yaratishda yozing:

const navbat = new Navbat<Buyurtma>();
const kesh = new Map<number, Mahsulot>();

✅ Yechim 2: maydon yoki o'zgaruvchi type'i bilan bering — TS undan oladi:

const navbat: Navbat<Buyurtma> = new Navbat(); // ✅ Navbat<Buyurtma>

✅ Yechim 3: boshlang'ich qiymat bo'lsa — constructor'ga bering, T o'zi aniqlanadi:

const kesh = new Map([[1, mahsulot]]); // Map<number, Mahsulot>

Esda tuting: generic class'ning constructor'i bo'sh bo'lsa, new Class<Type>() deb type'ni doim o'zingiz yozing.