How to Use TypeScript Classes with Simple Examples

TypeScript brings powerful features to JavaScript, including the concept of classes, which allows for object-oriented programming. Classes provide a blueprint for creating objects, encapsulating data, and defining behaviors. This guide will walk you through the basics of TypeScript classes with simple examples.

What is a Class?

A class is a blueprint for creating objects with predefined properties and methods. It helps in organizing code, promoting reusability, and creating scalable applications. Classes in TypeScript work similarly to classes in other object-oriented programming languages.

Defining a Basic Class

To define a class in TypeScript, use the class keyword followed by the class name and a set of curly braces containing properties and methods.

Basic Class Example

Below is an example of a simple Person class with properties and a method:

class Person {
  name: string;
  age: number;

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

  greet(): void {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

const person1 = new Person("Alice", 30);
person1.greet(); // Output: Hello, my name is Alice and I am 30 years old.

In this example, the Person class has two properties: name and age. The constructor method initializes these properties, and the greet method outputs a greeting message.

Access Modifiers

TypeScript provides three access modifiers to control the visibility of class members:

  • public: Members are accessible from anywhere (default).
  • private: Members are accessible only within the class.
  • protected: Members are accessible within the class and its subclasses.

Using Access Modifiers

Here’s how you can use access modifiers in a TypeScript class:

class Animal {
  public name: string;
  private age: number;

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

  public getAge(): number {
    return this.age;
  }
}

const dog = new Animal("Buddy", 5);
console.log(dog.name); // Output: Buddy
console.log(dog.getAge()); // Output: 5
// console.log(dog.age); // Error: 'age' is private and only accessible within class 'Animal'.

In this example, name is a public property, accessible from outside the class, while age is a private property, accessible only within the class.

Inheritance in TypeScript

TypeScript supports inheritance, which allows a class to inherit properties and methods from another class. This helps in reusing code and creating a hierarchy of classes.

Inheritance Example

Below is an example of a class Dog that inherits from a base class Animal:

class Animal {
  constructor(public name: string) {}

  makeSound(): void {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  constructor(name: string) {
    super(name); // Call the constructor of the base class
  }

  makeSound(): void {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog("Buddy");
dog.makeSound(); // Output: Buddy barks.

In this example, the Dog class extends the Animal class and overrides the makeSound method.

Getters and Setters

TypeScript allows you to define getters and setters for properties, providing controlled access to class members.

Getters and Setters Example

class Person {
  private _name: string;

  constructor(name: string) {
    this._name = name;
  }

  get name(): string {
    return this._name;
  }

  set name(newName: string) {
    if (newName) {
      this._name = newName;
    } else {
      console.log("Name cannot be empty.");
    }
  }
}

const person = new Person("Alice");
console.log(person.name); // Output: Alice
person.name = "Bob";
console.log(person.name); // Output: Bob

In this example, the name property is accessed and modified using getter and setter methods.

Conclusion

TypeScript classes are a powerful way to write object-oriented code in a clean and efficient manner. They provide a structured way to define properties, methods, access modifiers, inheritance, and more. By understanding how to use TypeScript classes, you can write more robust and maintainable code for your applications.