TypeScript - Classes: A Beginner's Guide

Hello there, future coding superstar! ? Are you ready to dive into the exciting world of TypeScript classes? Don't worry if you've never written a line of code before – we're going to start from scratch and build our way up. By the end of this tutorial, you'll be creating classes like a pro! So, let's get started on this adventure together.

TypeScript - Classes

What are Classes?

Before we jump into the nitty-gritty, let's understand what classes are. Think of a class as a blueprint for creating objects. Just like architects use blueprints to build houses, we use classes to create objects in our code. These objects can have properties (like the color of a house) and methods (like opening a door).

Creating Classes

Let's start by creating our first class. We'll create a simple Car class.

class Car {
  make: string;
  model: string;
  year: number;

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

  honk() {
    console.log("Beep beep!");
  }
}

Let's break this down:

  1. We start with the class keyword followed by the name of our class, Car.
  2. Inside the class, we define properties: make, model, and year.
  3. The constructor is a special method that's called when we create a new Car object. It sets up the initial values for our properties.
  4. We also have a honk method that, when called, will print "Beep beep!" to the console.

Creating Instance Objects

Now that we have our Car class, let's create some actual car objects!

let myCar = new Car("Toyota", "Corolla", 2020);
let yourCar = new Car("Honda", "Civic", 2019);

Here, we've created two Car objects: myCar and yourCar. The new keyword tells TypeScript to create a new instance of our Car class.

Accessing Attributes and Functions

Now that we have our car objects, how do we use them? Let's see:

console.log(myCar.make);  // Outputs: Toyota
console.log(yourCar.year);  // Outputs: 2019

myCar.honk();  // Outputs: Beep beep!

We use dot notation to access properties and methods of our objects. It's like saying, "Hey, myCar! What's your make?" or "Hey, myCar! Give us a honk!"

Class Inheritance

Inheritance is a powerful feature that allows us to create new classes based on existing ones. Let's create a SportsCar class that inherits from our Car class:

class SportsCar extends Car {
  topSpeed: number;

  constructor(make: string, model: string, year: number, topSpeed: number) {
    super(make, model, year);
    this.topSpeed = topSpeed;
  }

  race() {
    console.log(`Racing at ${this.topSpeed} mph!`);
  }
}

let mySpeedster = new SportsCar("Ferrari", "F8", 2021, 210);
mySpeedster.honk();  // Outputs: Beep beep!
mySpeedster.race();  // Outputs: Racing at 210 mph!

Here's what's happening:

  1. We use the extends keyword to inherit from Car.
  2. We add a new property topSpeed.
  3. In the constructor, we call super() to initialize the properties from the parent class.
  4. We add a new race method specific to SportsCar.

Our SportsCar has all the properties and methods of Car, plus its own additions!

Method Overriding

Sometimes, we want to change how a method from the parent class works in our child class. This is called method overriding. Let's override the honk method in our SportsCar:

class SportsCar extends Car {
  // ... previous code ...

  honk() {
    console.log("Vroom vroom!");
  }
}

mySpeedster.honk();  // Outputs: Vroom vroom!

Now when we call honk() on a SportsCar, it makes a sportier sound!

The static Keyword

The static keyword allows us to create properties and methods that belong to the class itself, not to instances of the class. Let's add a static method to our Car class:

class Car {
  // ... previous code ...

  static numberOfWheels() {
    return 4;
  }
}

console.log(Car.numberOfWheels());  // Outputs: 4

We can call this method on the Car class itself, without creating an instance.

The instanceof Operator

The instanceof operator allows us to check if an object is an instance of a particular class:

console.log(myCar instanceof Car);  // Outputs: true
console.log(mySpeedster instanceof SportsCar);  // Outputs: true
console.log(mySpeedster instanceof Car);  // Outputs: true
console.log(myCar instanceof SportsCar);  // Outputs: false

This is useful when you need to check what type of object you're dealing with.

Data Hiding

In TypeScript, we can use access modifiers to control the visibility of class members. The three access modifiers are public, private, and protected:

class BankAccount {
  private balance: number;

  constructor(initialBalance: number) {
    this.balance = initialBalance;
  }

  public deposit(amount: number) {
    this.balance += amount;
  }

  public withdraw(amount: number) {
    if (amount <= this.balance) {
      this.balance -= amount;
    } else {
      console.log("Insufficient funds!");
    }
  }

  protected getBalance() {
    return this.balance;
  }
}
  • private: Only accessible within the class.
  • public: Accessible from anywhere (default if not specified).
  • protected: Accessible within the class and its subclasses.

Classes and Interfaces

Interfaces in TypeScript allow us to define a contract for our classes. Let's create an interface for our Car class:

interface Vehicle {
  make: string;
  model: string;
  year: number;
  honk(): void;
}

class Car implements Vehicle {
  // ... implementation ...
}

By implementing an interface, we ensure that our class adheres to a specific structure.

Method Summary

Here's a summary of the methods we've covered in this tutorial:

Method Description
constructor() Initializes a new instance of a class
honk() Makes the car honk
race() Simulates racing (for SportsCar)
static numberOfWheels() Returns the number of wheels (for Car class)
deposit() Adds money to a bank account
withdraw() Removes money from a bank account
getBalance() Returns the current balance of a bank account

And there you have it! You've just taken your first steps into the world of TypeScript classes. Remember, practice makes perfect, so don't be afraid to experiment with these concepts. Create your own classes, mix and match different features, and most importantly, have fun coding! Who knows, maybe you'll be the one teaching this class next time! ?

Credits: Image by storyset