0
0
Typescriptprogramming~20 mins

Class implementing multiple interfaces in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Class implementing multiple interfaces
📖 Scenario: Imagine you are building a simple system to manage electronic devices. Each device can have different features like playing music and making calls. We want to organize these features using interfaces and then create a class that implements both.
🎯 Goal: Create two interfaces called MusicPlayer and Phone with specific methods. Then create a class called SmartDevice that implements both interfaces. Finally, create an instance of SmartDevice and call its methods to see the output.
📋 What You'll Learn
Create an interface called MusicPlayer with a method playMusic() that returns void.
Create an interface called Phone with a method makeCall(number: string) that returns void.
Create a class called SmartDevice that implements both MusicPlayer and Phone.
Inside SmartDevice, implement playMusic() to print "Playing music...".
Inside SmartDevice, implement makeCall(number: string) to print "Calling {number}..." using the given number.
Create an instance of SmartDevice called myDevice.
Call playMusic() and makeCall("123-456-7890") on myDevice and print the outputs.
💡 Why This Matters
🌍 Real World
In real life, devices often have multiple features. Using interfaces helps organize these features clearly and lets classes combine them as needed.
💼 Career
Understanding how to implement multiple interfaces is important for building flexible and maintainable code in TypeScript, a popular language for web and app development.
Progress0 / 4 steps
1
Create interfaces MusicPlayer and Phone
Create an interface called MusicPlayer with a method playMusic() that returns void. Also create an interface called Phone with a method makeCall(number: string) that returns void.
Typescript
Need a hint?

Use the interface keyword to define interfaces. Methods inside interfaces only have signatures without bodies.

2
Create class SmartDevice implementing both interfaces
Create a class called SmartDevice that implements both MusicPlayer and Phone.
Typescript
Need a hint?

Use implements keyword followed by both interface names separated by a comma.

3
Implement methods playMusic and makeCall in SmartDevice
Inside the SmartDevice class, implement the playMusic() method to print "Playing music...". Implement the makeCall(number: string) method to print "Calling {number}..." using the given number.
Typescript
Need a hint?

Use console.log to print messages. Use backticks ` and ${} to insert variables inside strings.

4
Create instance and call methods
Create an instance of SmartDevice called myDevice. Then call playMusic() and makeCall("123-456-7890") on myDevice.
Typescript
Need a hint?

Create the instance using new SmartDevice(). Then call the methods on this instance.