0
0
Typescriptprogramming~30 mins

Polymorphism through interfaces in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Polymorphism through interfaces
📖 Scenario: You are building a simple system to handle different types of notifications in an app. Each notification type should be able to send its message in its own way.
🎯 Goal: Create an interface called Notifier with a method send(). Then create two classes EmailNotifier and SMSNotifier that implement this interface. Finally, use polymorphism to call send() on both types of notifiers.
📋 What You'll Learn
Create an interface called Notifier with a method send() that returns void.
Create a class called EmailNotifier that implements Notifier and its send() method prints 'Sending email notification'.
Create a class called SMSNotifier that implements Notifier and its send() method prints 'Sending SMS notification'.
Create an array called notifiers of type Notifier[] containing instances of EmailNotifier and SMSNotifier.
Use a for loop to call send() on each notifier in the notifiers array.
Print the output of each send() call.
💡 Why This Matters
🌍 Real World
Many apps send notifications in different ways like email, SMS, or push notifications. Using interfaces and polymorphism helps manage these different types easily.
💼 Career
Understanding polymorphism and interfaces is key for writing flexible and maintainable code in TypeScript and many other programming languages.
Progress0 / 4 steps
1
Create the Notifier interface
Create an interface called Notifier with a method send() that returns void.
Typescript
Need a hint?

An interface defines a contract. Here, Notifier must have a send() method that returns nothing.

2
Create EmailNotifier and SMSNotifier classes
Create a class called EmailNotifier that implements Notifier with a send() method that prints 'Sending email notification'. Also create a class called SMSNotifier that implements Notifier with a send() method that prints 'Sending SMS notification'.
Typescript
Need a hint?

Use implements Notifier after the class name. The send() method should use console.log to print the messages.

3
Create an array of notifiers
Create an array called notifiers of type Notifier[] containing one instance of EmailNotifier and one instance of SMSNotifier.
Typescript
Need a hint?

Create the array with the exact name notifiers and include one instance of each notifier class.

4
Call send() on each notifier and print output
Use a for loop with variable notifier to iterate over the notifiers array and call notifier.send() inside the loop.
Typescript
Need a hint?

Use a for...of loop to call send() on each notifier. The output should show both messages.