0
0
Typescriptprogramming~3 mins

Why inheritance needs types in Typescript - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if your program could catch mistakes before running, just by knowing what each part should be?

The Scenario

Imagine you are building a program with different kinds of vehicles: cars, bikes, and trucks. You write separate code for each type, copying similar parts again and again without clear rules on what each vehicle can do.

The Problem

This manual way is slow and confusing. You might forget to add a needed feature to one vehicle or accidentally use a feature that doesn't belong. Without clear types, your program can break unexpectedly, and bugs hide in the mess.

The Solution

Using inheritance with types helps you create a clear blueprint for vehicles. Types tell the program what properties and actions each vehicle must have. This way, you avoid mistakes and make your code easier to understand and fix.

Before vs After
Before
class Car { drive() { console.log('Driving'); } }
class Bike { ride() { console.log('Riding'); } }
After
class Vehicle { drive(): void {} }
class Car extends Vehicle { drive() { console.log('Driving'); } }
What It Enables

It enables building reliable and organized programs where different objects share common features safely and clearly.

Real Life Example

Think of a game where you have many characters: warriors, archers, and mages. Using inheritance with types ensures all characters can perform basic actions like moving or attacking, while each has unique skills.

Key Takeaways

Manual coding without types causes confusion and errors.

Inheritance with types creates clear, reusable blueprints.

This leads to safer, easier-to-maintain code.