DEV Community

Cover image for My Journey with Classes and Objects in TypeScript: Lessons Learned!!!
Lingaraj H U
Lingaraj H U

Posted on

My Journey with Classes and Objects in TypeScript: Lessons Learned!!!

When I first started with TypeScript, classes and objects seemed daunting. But as I dug deeper, I discovered how powerful they can be. Let me share what I've learned along the way.

  • The Building Blocks: Basic Class Structure. I remember my first TypeScript class - it was a simple Car class:
class Car {
  make: string; // this is how you define the properties
  model: string;

  constructor(make: string, model: string) {
    this.make = make;
    this.model = model;
  }

  // A method to simulate driving the car
  drive() {
    console.log(`Cruising down the highway in my ${this.make} ${this.model}. What a ride!`);
  }
}

// Let's create new instance of the above class car.
const myDreamCar = new Car('Tesla', 'Model S');
myDreamCar.drive(); // Vrooom!
Enter fullscreen mode Exit fullscreen mode

This basic structure became my go-to template for creating objects. It's amazing how much you can do with just properties and methods!

  • Keeping Secrets: Access Modifiers As my projects grew, I needed to protect certain data. That's when I discovered access modifiers:
class PiggyBank {
  private savings: number; // Our secret stash!

  constructor(initialAmount: number) {
    this.savings = initialAmount;
  }

  // Public method to add money
  public deposit(amount: number) {
    this.savings += amount;
    console.log(`Cha-ching! Deposited ${amount}. New balance: ${this.savings}`);
  }

  // Protected method for inheritance purposes the only way to access this 
  // protected method by implementing the child of this class.

  protected getBalance() {
    return this.savings;
  }
}
Enter fullscreen mode Exit fullscreen mode

Using private and protected members felt like adding a security system to my code. No more accidental tampering!

  • The Family Tree: Inheritance Inheritance clicked for me when I thought about it in terms of a family tree:
class Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  move(distance: number = 0) {
    console.log(`${this.name} moved ${distance}m. They're on the go!`);
  }
}

class Dog extends Animal {
  bark() {
    console.log(`${this.name} says: Woof! Woof! Where's the mailman?`);
  }
}

// Let's create a furry friend!
const myPup = new Dog('Buddy');
myPup.bark();
myPup.move(10); // Buddy's on a mission!
Enter fullscreen mode Exit fullscreen mode

It was like creating a family of classes, with each child inheriting traits from its parent. Pretty cool, right?

  • Making Promises: Interfaces and Classes Interfaces helped me set clear expectations for my classes:
interface Vechicle {
  start(): void;
  stop(): void;
}

// when a class implements the interface you must define 
// the methods which are declared in that interface.

class Car implements Vechicle {
  start() {
    console.log('Engine purrs to life. Ready for adventure!');
  }
  stop() {
    console.log('Parking brake on. Journey complete!');
  }
}
Enter fullscreen mode Exit fullscreen mode

It's like making a promise: if a class implements an interface, it's guaranteed to have certain methods.

  • The Blueprint: Abstract Classes Abstract classes were a game-changer for creating flexible yet structured code:
// An abstract class is a blueprint for other classes.

// It can't be instantiated directly but can be inherited from.

abstract class Shape {

  // An abstract method doesn't have an implementation in the abstract class.

  // It must be implemented by any concrete (non-abstract) derived class.

  abstract getArea(): number; // abstract method

  // A concrete method in an abstract class has an implementation
  // and can be used by all derived classes.

  printArea() {
    console.log(`This shape covers ${this.getArea()} square units. Neat!`);
  }

}

// Circle is a concrete class that extends the abstract Shape class

class Circle extends Shape {

  // The 'private' keyword makes radius accessible only within this class

  constructor(private radius: number) {

    // 'super()' calls the constructor of the parent class (Shape)

    // It's required when extending a class, even if the parent class
    // doesn't have an explicit constructor

    super();

  }

  // This is the implementation of the abstract method from Shape

  getArea(): number {
    return Math.PI * this.radius ** 2;
  }

}

// We can create an instance of Circle, but not of Shape

const frisbee = new Circle(5);

// This calls printArea() from Shape, which in turn calls getArea() from Circle

frisbee.printArea();
// Outputs: This shape covers 78.53981633974483 square units. Neat!
Enter fullscreen mode Exit fullscreen mode

Learning about classes and objects in TypeScript has been a journey. Each concept opened up new possibilities in my coding adventures. Whether you're building a simple app or a complex system, these tools can help you write cleaner, more organized code.

Hope you learnt something new....!!!!. thank you reading till the end :)

Top comments (0)