0
0
Typescriptprogramming~15 mins

Implementing interfaces in classes in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Implementing interfaces in classes
📖 Scenario: You are building a simple system to manage different types of vehicles. Each vehicle must have a method to display its details.
🎯 Goal: Create an interface called Vehicle with a method displayInfo(). Then create a class Car that implements this interface and shows the car's brand and model.
📋 What You'll Learn
Create an interface named Vehicle with a method displayInfo() that returns void
Create a class named Car that implements the Vehicle interface
Add a constructor to Car that takes brand and model as string parameters
Implement the displayInfo() method in Car to print the brand and model
Create an instance of Car with brand "Toyota" and model "Corolla"
Call the displayInfo() method on the Car instance
💡 Why This Matters
🌍 Real World
Interfaces help define clear contracts for classes in large applications, ensuring consistent behavior across different objects.
💼 Career
Understanding interfaces and class implementation is essential for TypeScript developers building scalable and maintainable codebases.
Progress0 / 4 steps
1
Create the Vehicle interface
Create an interface called Vehicle with a method displayInfo() that returns void.
Typescript
Need a hint?

Use the interface keyword and define displayInfo() with no parameters and return type void.

2
Create the Car class implementing Vehicle
Create a class called Car that implements the Vehicle interface. Add a constructor with parameters brand and model of type string, and store them as public properties.
Typescript
Need a hint?

Use implements Vehicle after the class name. Use public in constructor parameters to create properties automatically.

3
Implement the displayInfo() method
Inside the Car class, implement the displayInfo() method to print the message "Car: {brand} {model}" using console.log and template strings.
Typescript
Need a hint?

Use console.log with backticks ` and ${} to insert variables.

4
Create Car instance and call displayInfo()
Create a variable myCar as a new Car with brand "Toyota" and model "Corolla". Then call myCar.displayInfo() to print the car details.
Typescript
Need a hint?

Create the instance with new Car("Toyota", "Corolla") and call displayInfo().