0
0
Typescriptprogramming~30 mins

Why inheritance needs types in Typescript - See It in Action

Choose your learning style9 modes available
Why inheritance needs types
📖 Scenario: Imagine you are building a simple system to manage different types of vehicles. Each vehicle has some common features, but specific types like cars and trucks have their own special features.
🎯 Goal: You will create a base class for vehicles and two child classes for car and truck. You will use TypeScript types to make sure each class has the right properties and methods. This will show why types are important when using inheritance.
📋 What You'll Learn
Create a base class called Vehicle with a make and model property
Create a class called Car that inherits from Vehicle and adds a seats property
Create a class called Truck that inherits from Vehicle and adds a capacity property
Create a variable called myCar of type Car with specific values
Create a variable called myTruck of type Truck with specific values
Print the details of myCar and myTruck to show their types and properties
💡 Why This Matters
🌍 Real World
Inheritance with types is used in software to organize related objects like vehicles, employees, or products, making code easier to manage and understand.
💼 Career
Understanding inheritance and types is essential for writing clear, safe, and maintainable code in many programming jobs, especially when working with object-oriented languages like TypeScript.
Progress0 / 4 steps
1
Create the base class Vehicle
Create a class called Vehicle with a constructor that takes make (string) and model (string) and assigns them to public properties.
Typescript
Need a hint?

Use class Vehicle and a constructor with public parameters to create properties easily.

2
Create Car and Truck classes inheriting Vehicle
Create a class called Car that extends Vehicle and adds a public seats (number) property. Also create a class called Truck that extends Vehicle and adds a public capacity (number) property. Use constructors to set all properties.
Typescript
Need a hint?

Use extends Vehicle and call super(make, model) inside constructors.

3
Create instances of Car and Truck
Create a variable called myCar of type Car with make 'Toyota', model 'Corolla', and seats 5. Create a variable called myTruck of type Truck with make 'Ford', model 'F-150', and capacity 1000.
Typescript
Need a hint?

Create variables with const and use new Car(...) and new Truck(...).

4
Print details of myCar and myTruck
Print the details of myCar and myTruck using console.log. Show the make, model, and seats for myCar, and make, model, and capacity for myTruck.
Typescript
Need a hint?

Use console.log with template strings to show the properties.