0
0
Typescriptprogramming~30 mins

Type compatibility with classes in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Type Compatibility with Classes
📖 Scenario: Imagine you are building a simple system to manage different types of vehicles. Each vehicle has a name and a method to display its details. You want to understand how TypeScript checks if one class can be used where another is expected, based on their structure.
🎯 Goal: You will create two classes with similar properties and methods, then check if an instance of one class can be assigned to a variable typed as the other class. This will help you learn about type compatibility in TypeScript classes.
📋 What You'll Learn
Create a class called Car with a name property and a display() method.
Create a class called Bike with a name property and a display() method.
Create a variable called vehicle typed as Car.
Assign an instance of Bike to the vehicle variable to demonstrate type compatibility.
Print the name property of vehicle.
💡 Why This Matters
🌍 Real World
Understanding type compatibility helps when working with different but similar objects, like vehicles, users, or shapes, allowing flexible and safe code.
💼 Career
Many TypeScript jobs require knowledge of how classes and interfaces relate, so you can design clean and maintainable code that works well with different data types.
Progress0 / 4 steps
1
Create the Car class
Create a class called Car with a name property set through the constructor and a display() method that logs the text "Car: " followed by the name.
Typescript
Need a hint?

Use class Car with a constructor to set name. The display() method should print the car's name.

2
Create the Bike class
Create a class called Bike with a name property set through the constructor and a display() method that logs the text "Bike: " followed by the name.
Typescript
Need a hint?

Similar to Car, create Bike with the same property and method names but different console text.

3
Assign Bike instance to Car variable
Create a variable called vehicle typed as Car and assign to it a new instance of Bike with the name "Speedster".
Typescript
Need a hint?

Declare vehicle as type Car and assign it a new Bike instance.

4
Print the vehicle name
Write a line to print the name property of the vehicle variable.
Typescript
Need a hint?

Use console.log(vehicle.name) to print the name.