TypeScript Classes and Interfaces: Object-Oriented Programming

Are you ready to take your TypeScript skills to the next level? Do you want to learn how to write more organized and maintainable code using object-oriented programming (OOP) principles? If so, you've come to the right place! In this article, we'll explore TypeScript classes and interfaces, two key concepts in OOP that will help you write better code.

What is Object-Oriented Programming?

Before we dive into TypeScript classes and interfaces, let's first define what we mean by object-oriented programming. OOP is a programming paradigm that focuses on creating objects that have properties and methods. These objects can interact with each other to perform tasks and solve problems.

OOP has several benefits, including:

TypeScript Classes

In TypeScript, a class is a blueprint for creating objects. It defines the properties and methods that an object will have. Here's an example of a simple TypeScript class:

class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
  }
}

In this example, we've defined a Person class with two properties (name and age) and one method (sayHello). The constructor method is used to initialize the properties when a new object is created.

To create a new Person object, we can use the new keyword:

const john = new Person('John', 30);
john.sayHello(); // Output: "Hello, my name is John and I'm 30 years old."

As you can see, we've created a new Person object named john and called the sayHello method on it. This method uses the name and age properties to output a greeting.

Inheritance

One of the key features of OOP is inheritance, which allows you to create new classes based on existing ones. In TypeScript, you can use the extends keyword to create a subclass that inherits properties and methods from a parent class.

Here's an example:

class Employee extends Person {
  jobTitle: string;

  constructor(name: string, age: number, jobTitle: string) {
    super(name, age);
    this.jobTitle = jobTitle;
  }

  introduce() {
    console.log(`Hi, my name is ${this.name}, I'm ${this.age} years old, and I'm a ${this.jobTitle}.`);
  }
}

In this example, we've created a new Employee class that extends the Person class. The Employee class has an additional property (jobTitle) and a new method (introduce).

To create a new Employee object, we can use the same syntax as before:

const jane = new Employee('Jane', 25, 'Software Engineer');
jane.introduce(); // Output: "Hi, my name is Jane, I'm 25 years old, and I'm a Software Engineer."

As you can see, we've created a new Employee object named jane and called the introduce method on it. This method uses the name, age, and jobTitle properties to output an introduction.

Access Modifiers

In TypeScript, you can use access modifiers to control the visibility of properties and methods. There are three access modifiers:

Here's an example:

class BankAccount {
  private balance: number;

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

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

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

  getBalance() {
    return this.balance;
  }
}

In this example, we've defined a BankAccount class with a balance property and three methods (deposit, withdraw, and getBalance). The balance property is marked as private, which means it can only be accessed from within the class.

To use this class, we can create a new BankAccount object and call its methods:

const account = new BankAccount(1000);
account.deposit(500);
account.withdraw(200);
console.log(account.getBalance()); // Output: 1300

As you can see, we've created a new BankAccount object named account and called its deposit, withdraw, and getBalance methods. The balance property is not accessible from outside the class.

TypeScript Interfaces

In TypeScript, an interface is a way to define a contract for an object. It specifies the properties and methods that an object must have in order to be considered a valid instance of that interface.

Here's an example of a simple TypeScript interface:

interface Animal {
  name: string;
  age: number;
  speak(): void;
}

In this example, we've defined an Animal interface with two properties (name and age) and one method (speak). The speak method has a return type of void, which means it doesn't return anything.

To create an object that implements this interface, we can use the following syntax:

const dog: Animal = {
  name: 'Fido',
  age: 5,
  speak() {
    console.log('Woof!');
  }
};

dog.speak(); // Output: "Woof!"

As you can see, we've created a new object that implements the Animal interface and called its speak method.

Optional Properties

In TypeScript interfaces, you can mark properties as optional by adding a ? after their name. This means that an object can have the property, but it's not required.

Here's an example:

interface Person {
  name: string;
  age: number;
  email?: string;
}

In this example, we've defined a Person interface with two required properties (name and age) and one optional property (email).

To create an object that implements this interface, we can use the following syntax:

const john: Person = {
  name: 'John',
  age: 30
};

const jane: Person = {
  name: 'Jane',
  age: 25,
  email: 'jane@example.com'
};

As you can see, we've created two objects that implement the Person interface. The first object (john) doesn't have an email property, while the second object (jane) does.

Readonly Properties

In TypeScript interfaces, you can mark properties as readonly by adding the keyword before their name. This means that the property can't be changed once it's set.

Here's an example:

interface Point {
  readonly x: number;
  readonly y: number;
}

In this example, we've defined a Point interface with two readonly properties (x and y).

To create an object that implements this interface, we can use the following syntax:

const point: Point = {
  x: 10,
  y: 20
};

point.x = 5; // Error: Cannot assign to 'x' because it is a read-only property.

As you can see, we've created a new object that implements the Point interface. Once the x and y properties are set, they can't be changed.

Conclusion

In this article, we've explored TypeScript classes and interfaces, two key concepts in object-oriented programming. We've seen how classes can be used to create blueprints for objects, how inheritance can be used to create subclasses, and how access modifiers can be used to control visibility. We've also seen how interfaces can be used to define contracts for objects, how optional properties and readonly properties can be used, and how objects can implement multiple interfaces.

By mastering these concepts, you'll be able to write more organized and maintainable code in TypeScript. So what are you waiting for? Start practicing and take your TypeScript skills to the next level!

Editor Recommended Sites

AI and Tech News
Best Online AI Courses
Classic Writing Analysis
Tears of the Kingdom Roleplay
NFT Bundle: Crypto digital collectible bundle sites from around the internet
Cloud Checklist - Cloud Foundations Readiness Checklists & Cloud Security Checklists: Get started in the Cloud with a strong security and flexible starter templates
ML Writing: Machine learning for copywriting, guide writing, book writing
Data Ops Book: Data operations. Gitops, secops, cloudops, mlops, llmops
Best Scifi Games - Highest Rated Scifi Games & Top Ranking Scifi Games: Find the best Scifi games of all time