Series: TypeScript Basics Lesson 70

Interface implementation

TypeScript'da implements: class'ning interface shartnomasiga rozi bo'lishi, to'lov tizimi misoli, shartnoma buzilganda xato, bir nechta interface va muhim qoidalar.

70-dars

Interface implementation

Interface — bu shartnoma: "Kim meni ishlatsa, unda albatta mana shu metodlar bo'lishi kerak." implements esa class'ning shu shartnomaga rozi ekanini bildiradi. TypeScript class'ni tekshiradi va biror metod yetishmasa, darhol xato beradi.

Hayotiy o'xshatish: rozetka standarti — interface, har xil zaryadlovchilar esa — class'lar. Standartga mos har qanday zaryadlovchi rozetkaga tushadi.

Real misol (to'lov tizimi)

interface Payment {
  pay(amount: number): void;
}

class Click implements Payment {
  pay(amount: number) {
    console.log(`Click orqali ${amount} so'm`);
  }
}

class Payme implements Payment {
  pay(amount: number) {
    console.log(`Payme orqali ${amount} so'm`);
  }
}

function checkout(method: Payment) {
  method.pay(50000);
}

checkout(new Click()); // Click orqali 50000 so'm
checkout(new Payme()); // Payme orqali 50000 so'm

Nega kerak?

checkout funksiyasi qaysi to'lov kelganini bilmaydi, unga faqat pay metodi borligi muhim. Ertaga Uzum qo'shsangiz, checkout'ni o'zgartirmaysiz, yangi class yozasiz, xolos.

Shartnoma buzilsa

class Uzum implements Payment {}
// ❌ Class 'Uzum' incorrectly implements interface 'Payment'.
//      Property 'pay' is missing in type 'Uzum' but required in type 'Payment'.

Bir nechta interface

Class bir vaqtda bir nechta shartnomaga rozi bo'lishi mumkin — ular vergul bilan yoziladi:

interface Refundable {
  refund(amount: number): void;
}

class Click implements Payment, Refundable {
  pay(amount: number) {
    console.log(`Click orqali ${amount} so'm to'landi`);
  }

  refund(amount: number) {
    console.log(`Click orqali ${amount} so'm qaytarildi`);
  }
}

Eslab qoling

  • Class'da interface'dagidan ko'proq metod bo'lishi mumkin, lekin kam bo'lishi mumkin emas.
  • implements parametr type'ini o'zi qo'ymaydi — amount: number'ni class'da ham yozasiz:
class Paynet implements Payment {
  pay(amount) {
    // ❌ Parameter 'amount' implicitly has an 'any' type.
    console.log(amount);
  }
}

implements faqat tekshiradi: "class shartnomaga mosmi?". U class'ga hech qanday type'ni "meros qilib bermaydi".