Getter va Setter — TypeScript da

~15 daq · TypeScript · OOP

temperature xususiyati Celsius da saqlanadi — lekin Fahrenheit da ham o'qish kerak. Yoki fullName getter — ism va familya dan avtomatik hosil bo'lishi. Getter/setter — xususiyat ko'rinishida, ammo funksiya kabi ishlaydi.


Getter — get

class Foydalanuvchi {
  private _ism:     string;
  private _familya: string;

  constructor(ism: string, familya: string) {
    this._ism     = ism;
    this._familya = familya;
  }

  get toliIsm(): string {
    return `${this._ism} ${this._familya}`;
  }
}

const u = new Foydalanuvchi("Jasur", "Normatov");
u.toliIsm; // "Jasur Normatov" — metoddek chaqirilmaydi, xususiyatdek

Setter — set

class Harorat {
  private _celsius: number = 0;

  get celsius(): number { return this._celsius; }
  set celsius(q: number) {
    if (q < -273.15) throw new Error("Absolyut noldan past bo'lmaydi");
    this._celsius = q;
  }

  get fahrenheit(): number {
    return this._celsius * 9/5 + 32;
  }

  set fahrenheit(q: number) {
    this.celsius = (q - 32) * 5/9; // celsius setter orqali — tekshiruv ishlaydi
  }
}

const h = new Harorat();
h.celsius    = 100;  // ✅
h.fahrenheit;        // 212
h.fahrenheit = 32;   // ✅ — celsius = 0
h.celsius    = -300; // ❌ — xato

Getter turlari

TypeScript getter qaytish turini o'zi aniqlaydi. Alohida yozish shart emas — lekin yozish mumkin:

class Example {
  private _qiymat = 0;

  get qiymat(): number { // tur ixtiyoriy
    return this._qiymat;
  }
}

Getter — lazy initialization

class Konfiguratsiya {
  private _malumot: Record<string, string> | null = null;

  get malumot(): Record<string, string> {
    if (!this._malumot) {
      this._malumot = this.yuklash(); // birinchi marta chaqirilganda
    }
    return this._malumot;
  }

  private yuklash(): Record<string, string> {
    return { host: "localhost", port: "5432" };
  }
}

Tez-tez uchraydigan xatolar

Setter turi getter turiga mos kelmasligi:

class Example {
  private _x = 0;

  get x(): number   { return this._x; }
  set x(v: string) { this._x = Number(v); }
  // ❌ — TypeScript: get va set turi bir xil bo'lishi kerak (4.3+ dan farqlash mumkin)
}

// ✅ — bir xil tur
set x(v: number) { this._x = v; }

Faqat getter — readonly xususiyat:

class Circle {
  constructor(private radius: number) {}

  get area(): number { return Math.PI * this.radius ** 2; }
  // set area — yo'q → area readonly
}

const c = new Circle(5);
c.area = 10; // ❌ — setter yo'q

Xulosa

class Example {
  private _x: number = 0;

  get x(): number  { return this._x; }       // o'qilganda
  set x(v: number) { this._x = Math.abs(v); } // yozilganda

  get readonly(): number { return 42; } // faqat o'qish — setter yo'q
}

const e = new Example();
e.x;      // getter chaqiriladi
e.x = -5; // setter chaqiriladi, Math.abs → 5

Keyingi dars

42-dars: Static members va static initialization blocks