Implementing Interfaces
Implementing Interfaces
π¨βπΌ Let's build a payment system with different payment methods. We'll use
interfaces to ensure all payment methods follow the same contract.
π¨ Open
and:
- Create a
PaymentMethodinterface with:pay(amount: number): string
- Create and export a
CreditCardclass thatimplements PaymentMethod:- Public field:
cardNumber(string) - Constructor
(cardNumber: string) pay(amount)returns exactly:Paid $${amount} with credit card ${cardNumber}
- Public field:
- Create and export a
PayPalclass thatimplements PaymentMethod:- Public field:
email(string) - Constructor
(email: string) pay(amount)returns exactly:Paid $${amount} with PayPal ${email}
- Public field:
- Export the classes:
export { CreditCard, PayPal }(PaymentMethoditself does not need to be exported)
Fixtures and success criteria
const creditCard = new CreditCard('1234-5678-9012-3456')
const paypal = new PayPal('user@example.com')
creditCard.cardNumber === '1234-5678-9012-3456'creditCard.pay(100) === 'Paid $100 with credit card 1234-5678-9012-3456'paypal.email === 'user@example.com'paypal.pay(50) === 'Paid $50 with PayPal user@example.com'- Both instances expose a callable
paymethod
π° Classes that implement an interface must define all its methods.


