Generic class — tur parametrli sinflar

~15 daq · TypeScript · Generics

Stack (oxirdan qo'shib, oxirdan olib chiqadigan to'plam) yozmoqchisiz. Sonlar uchun, matnlar uchun, ob'ektlar uchun — mantiq bir xil. Generic class — bir class, har tur bilan ishlaydi.


Generic class

class Stack<T> {
  private elementlar: T[] = [];

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

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

  tepa(): T | undefined {
    return this.elementlar[this.elementlar.length - 1];
  }

  uzunlik(): number {
    return this.elementlar.length;
  }
}

Ishlatish:

const sonStack = new Stack<number>();
sonStack.qosh(1);
sonStack.qosh(2);
sonStack.ol(); // 2 — number ✅

const matnStack = new Stack<string>();
matnStack.qosh("Ali");
matnStack.qosh("Vali");
matnStack.ol(); // "Vali" — string ✅

Tur inference

const stack = new Stack<number>();
// yoki TypeScript o'zi tushunadi:
stack.qosh(1); // T = number deb aniqlanadi
stack.qosh("salom"); // ❌ — string emas, number kerak

Generic class — bir nechta parametr

class Juft<Kalit, Qiymat> {
  private malumot = new Map<Kalit, Qiymat>();

  qo_y(k: Kalit, q: Qiymat): void {
    this.malumot.set(k, q);
  }

  ol(k: Kalit): Qiymat | undefined {
    return this.malumot.get(k);
  }
}

const lug_at = new Juft<string, number>();
lug_at.qo_y("yoshlar", 25);
lug_at.ol("yoshlar"); // number ✅

Constraint bilan generic class

interface IdLi { id: number; }

class Omborxona<T extends IdLi> {
  private xazina: Map<number, T> = new Map();

  saqlash(element: T): void {
    this.xazina.set(element.id, element);
  }

  olish(id: number): T | undefined {
    return this.xazina.get(id);
  }
}

const foydalanuvchilar = new Omborxona<{ id: number; ism: string }>();
foydalanuvchilar.saqlash({ id: 1, ism: "Jasur" });
foydalanuvchilar.olish(1); // { id: number; ism: string } ✅

Tez-tez uchraydigan xatolar

Static metodda tur parametri:

class Box<T> {
  static qiymat: T; // ❌ — static metodda T ishlatib bo'lmaydi
  static yaratish<T>(x: T): Box<T> { // ✅ — alohida T
    return new Box<T>();
  }
}

Static memberlarda class ning T parametri ishlatilmaydi — alohida generic parametr yozish kerak.


Xulosa

class Konteyner<T> {
  private qiymat: T;
  constructor(q: T) { this.qiymat = q; }
  ol(): T { return this.qiymat; }
  qo_y(q: T): void { this.qiymat = q; }
}

const son  = new Konteyner<number>(42);
const matn = new Konteyner<string>("salom");

// T instance yaratishda aniqlanadi
// Static da T ishlatilmaydi

Keyingi dars

36-dars: Constraint (extends) va default type parametr