0
0
Typescriptprogramming~30 mins

Method overriding with types in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Method overriding with types
📖 Scenario: Imagine you are creating a simple system for different types of vehicles. Each vehicle can describe itself with a method. Some vehicles have extra details to share.
🎯 Goal: You will create a base class with a method, then create a subclass that overrides this method with a more specific return type.
📋 What You'll Learn
Create a base class called Vehicle with a method describe() that returns a string.
Create a subclass called Car that extends Vehicle.
Override the describe() method in Car to return a more specific type: an object with make and model properties.
Print the results of calling describe() on both Vehicle and Car instances.
💡 Why This Matters
🌍 Real World
Method overriding is common in software when different objects share behavior but need to customize details. For example, different vehicle types describe themselves differently.
💼 Career
Understanding method overriding and type safety is important for writing clear, maintainable TypeScript code in many software development jobs.
Progress0 / 4 steps
1
Create the base class Vehicle
Create a class called Vehicle with a method describe() that returns the string 'This is a vehicle.'
Typescript
Need a hint?

Use class Vehicle {} and inside it define describe(): string { return 'This is a vehicle.'; }

2
Create the subclass Car
Create a class called Car that extends Vehicle.
Typescript
Need a hint?

Use class Car extends Vehicle {} to create the subclass.

3
Override describe() in Car with a specific return type
In the Car class, override the describe() method to return an object with make and model properties, both strings. For example, return { make: 'Toyota', model: 'Corolla' }.
Typescript
Need a hint?

Define describe() with return type { make: string; model: string } and return the object.

4
Print the descriptions from Vehicle and Car
Create an instance of Vehicle called vehicle and an instance of Car called car. Then print the results of vehicle.describe() and car.describe() using console.log.
Typescript
Need a hint?

Use const vehicle = new Vehicle(); and const car = new Car();, then console.log(vehicle.describe()); and console.log(car.describe());.