Series: TypeScript Basics Lesson 36

this typing

TypeScript'da this'ni type'lash: this parametri, chaqiruv paytidagi tekshiruv, obyekt va class method'lari, arrow funksiya, callback'larda this: void, this qaytish type'i va method'ni uzatishda this'ni yo'qotish.

36-dars

this typing

JavaScript'da this funksiya qanday chaqirilganiga qarab o'zgaradi, qayerda yozilganiga qarab emas. TS buni oddiy funksiyada oldindan bila olmaydi, shuning uchun thisni type'siz qoldirsak, u any bo'lib qoladi.

type User = { name: string; age: number };

// ❌ Muammo: this'ning type'i noma'lum
function greet() {
  return `Salom, ${this.name}`;
  // ❌ 'this' implicitly has type 'any' because it does not have a type annotation.
}

Bu xato noImplicitThis (u strict ichida bor) yoqilganda chiqadi. O'chiq bo'lsa, this.nmae kabi imlo xatolari ham jim o'tib ketadi.

// ✅ Yechim: this'ning type'ini maxsus "this parametri" bilan e'lon qilamiz
function greet(this: User) {
  return `Salom, ${this.name}`; // ✅ this: User
}

const user: User = { name: "Ali", age: 25 };

greet.call(user); // ✅ "Salom, Ali"
greet();
// ❌ The 'this' context of type 'void' is not assignable to method's 'this' of type 'User'.

Endi TS ikkala tomonni tekshiradi: funksiya ichida this to'g'ri ishlatiladi, chaqiruvchi esa to'g'ri this bilan chaqiradi.

Qanday ishlaydi?

1. this parametri — soxta parametr

this parametri doim birinchi o'rinda yoziladi, lekin u haqiqiy argument emas. Kompilyatsiyadan keyin butunlay o'chib ketadi.

// TypeScript
function setAge(this: User, age: number) {
  this.age = age;
}
// Kompilyatsiyadan keyingi JavaScript
function setAge(age) {
  this.age = age;
}

Shuning uchun chaqiruvda uni hisobga olmaymiz: setAge bitta argument kutadi — age.

setAge.call(user, 30); // ✅ this = user, age = 30

2. Chaqiruv paytidagi tekshiruv

TS this qayerdan kelishini chaqiruv shakliga qarab aniqlaydi.

function describe(this: User) {
  return `${this.name}, ${this.age} yosh`;
}

// 1) Obyekt method'i sifatida
const person = { name: "Vali", age: 30, describe };
person.describe(); // ✅ this = person

// 2) call / apply / bind bilan (strictBindCallApply)
describe.call({ name: "Ali", age: 25 }); // ✅
describe.call({ name: "Ali" });
// ❌ Argument of type '{ name: string; }' is not assignable to parameter of type 'User'.
//      Property 'age' is missing in type '{ name: string; }' but required in type 'User'.

// 3) Oddiy chaqiruv — this yo'q
describe();
// ❌ The 'this' context of type 'void' is not assignable to method's 'this' of type 'User'.

3. Obyekt literal method'larida this avtomatik

Obyekt ichida method yozilganda TS thisni o'sha obyekt type'i deb oladi — annotatsiya shart emas.

const counter = {
  count: 0,
  increment() {
    this.count++; // this: { count: number; increment(): void }
    this.cout++;
    // ❌ Property 'cout' does not exist on type '{ count: number; increment(): void; }'. Did you mean 'count'?
  },
};

Class method'larida ham xuddi shunday: this — class instance'i.

4. Arrow funksiyada o'z this yo'q

Arrow funksiya thisni o'zi yozilgan tashqi joydan oladi (lexical this). Shuning uchun unga this parametri berib bo'lmaydi.

const fn = (this: User) => {};
// ❌ An arrow function cannot have a 'this' parameter.

Bu xususiyat class ichida juda foydali: arrow funksiya class instance'ining thisini "ushlab qoladi".

class Timer {
  seconds = 0;

  start() {
    setInterval(() => {
      this.seconds++; // ✅ this: Timer — arrow tashqi this'ni oldi
    }, 1000);

    setInterval(function () {
      this.seconds++;
      // ❌ 'this' implicitly has type 'any' because it does not have a type annotation.
    }, 1000);
  }
}
Funksiya turi this qayerdan keladi this parametri yozish mumkinmi
function e'lon / ifoda chaqiruv shaklidan ✅
Obyekt / class method'i chaqiruv shaklidan (odatda obyekt) ✅
Arrow funksiya yozilgan tashqi joydan ❌

5. Callback type'larida this

Callback type'ida this ham ko'rsatiladi. DOM'dagi addEventListener shunday ishlaydi: oddiy function bilan yozilgan handler'da this — element.

const button = document.querySelector("button")!;

button.addEventListener("click", function () {
  this.disabled = true; // ✅ this: HTMLButtonElement
});

O'z API'ingizda esa this: void yozib, callback thisga tayanmasligini talab qilishingiz mumkin:

function onTick(handler: (this: void, tick: number) => void) {
  let tick = 0;
  setInterval(() => handler(++tick), 1000);
}

class Clock {
  time = 0;
  update(this: Clock, tick: number) {
    this.time = tick;
  }
}

const clock = new Clock();
onTick(clock.update);
// ❌ Argument of type '(this: Clock, tick: number) => void' is not assignable to parameter of type '(this: void, tick: number) => void'.
//      The 'this' types of each signature are incompatible.
//        Type 'void' is not assignable to type 'Clock'.

onTick((tick) => clock.update(tick)); // ✅ this saqlanadi

6. this qaytish type'i — zanjirli chaqiruv

Method qaytish type'i sifatida this yozilsa, u "joriy class'ning instance'i" degani. Meros olingan class'da ham to'g'ri type qaytadi.

class QueryBuilder {
  protected parts: string[] = [];

  where(condition: string): this {
    this.parts.push(`WHERE ${condition}`);
    return this;
  }
}

class UserQuery extends QueryBuilder {
  active(): this {
    this.parts.push("AND active = 1");
    return this;
  }
}

new UserQuery().where("age > 18").active(); // ✅ where() UserQuery qaytardi

Agar where qaytish type'i QueryBuilder deb yozilganda, .active() chaqirib bo'lmas edi: Property 'active' does not exist on type 'QueryBuilder'.

this type guard'larda ham ishlatiladi (this is ...).

Eng ko'p uchraydigan xato

Class method'ini callback sifatida berib, thisni yo'qotish.

class Counter {
  count = 0;

  increment() {
    this.count++;
  }
}

const counter = new Counter();

setTimeout(counter.increment, 1000);                 // 🐛 TS jim
button.addEventListener("click", counter.increment); // 🐛 TS jim

// 1 soniyadan keyin:
console.log(counter.count); // 0 — o'zgarmadi!

Nega bunday bo'ladi? counter.increment yozilganda method obyektdan "uzib olinadi" — faqat funksiyaning o'zi uzatiladi. Keyin uni setTimeout yoki addEventListener o'zicha chaqiradi va this endi counter emas: brauzerda setTimeout uchun window, click uchun esa button bo'ladi. this.count++ boshqa obyektga yoziladi, counter.count esa o'zgarmaydi. Xato chiqmaydi, faqat natija noto'g'ri.

TS bu yerda indamaydi, chunki class method'larida this parametri aniq yozilmagan va TS chaqiruv shaklini kuzatmaydi. setTimeout handler'ining type'i esa juda keng.

// ✅ 1-yechim: arrow funksiya bilan o'rab berish
setTimeout(() => counter.increment(), 1000);

// ✅ 2-yechim: bind bilan this'ni bog'lash
button.addEventListener("click", counter.increment.bind(counter));

// ✅ 3-yechim: method'ni arrow class field qilish — this doim instance
class Counter2 {
  count = 0;
  increment = () => {
    this.count++; // this har doim Counter2 instance'i
  };
}

const c2 = new Counter2();
setTimeout(c2.increment, 1000); // ✅ ishlaydi

3-yechim React class komponentlarida va event handler'larda keng tarqalgan. Kamchiligi: arrow field har bir instance uchun alohida funksiya yaratadi va prototype'da bo'lmaydi.

O'z API'ingizni yozayotganda esa callback type'iga this: void qo'ying — shunda bu xatoni TS o'zi ushlaydi.

Esda tuting: obj.methodni qavssiz uzatganingizda this u bilan birga ketmaydi — arrow bilan o'rang, bind qiling yoki method'ni arrow field qiling.