Does TypeScript Have Classes?

TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript. One of the key features borrowed from object - oriented programming languages is the concept of classes. Classes in TypeScript provide a way to create reusable and organized code structures, similar to how they work in languages like Java or C#. This blog will delve into the details of classes in TypeScript, covering their fundamental concepts, usage methods, common practices, and best practices.

Table of Contents

  1. Fundamental Concepts of Classes in TypeScript
  2. Usage Methods of Classes in TypeScript
  3. Common Practices with TypeScript Classes
  4. Best Practices for Using TypeScript Classes
  5. Conclusion
  6. References

1. Fundamental Concepts of Classes in TypeScript

What are Classes?

A class in TypeScript is a blueprint for creating objects. It encapsulates data and the functions that manipulate that data. A class can have properties (variables) and methods (functions).

Class Declaration

Here is a basic example of a class declaration in TypeScript:

class Person {
    name: string;
    age: number;

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

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

In this example:

  • Person is the name of the class.
  • name and age are properties of the class.
  • The constructor is a special method that is called when an object of the class is created. It initializes the properties of the object.
  • greet is a method that returns a greeting message.

Creating an Object from a Class

To create an object from a class, we use the new keyword:

const person = new Person("John", 30);
console.log(person.greet()); 

2. Usage Methods of Classes in TypeScript

Inheritance

TypeScript supports inheritance, which allows a class to inherit properties and methods from another class. The class that is being inherited from is called the base class or parent class, and the class that inherits is called the derived class or child class.

class Employee extends Person {
    employeeId: number;

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

    getEmployeeInfo() {
        return `${this.greet()} My employee ID is ${this.employeeId}.`;
    }
}

const employee = new Employee("Jane", 25, 123);
console.log(employee.getEmployeeInfo());

In this example, the Employee class extends the Person class. The super keyword is used to call the constructor of the parent class.

Access Modifiers

TypeScript has three access modifiers: public, private, and protected.

  • public: A public member can be accessed from anywhere. By default, all members of a class are public.
  • private: A private member can only be accessed within the class where it is declared.
  • protected: A protected member can be accessed within the class where it is declared and in its derived classes.
class Animal {
    private name: string;

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

    getName() {
        return this.name;
    }
}

const animal = new Animal("Dog");
// console.log(animal.name); // This will cause a compilation error
console.log(animal.getName()); 

3. Common Practices with TypeScript Classes

Encapsulation

Encapsulation is the practice of bundling data with the methods that operate on that data. By using access modifiers, we can control the access to the data and ensure that it is modified in a controlled way. For example, in the Animal class above, the name property is private, and we use a public method getName to access it.

Method Overriding

Method overriding allows a derived class to provide a specific implementation of a method that is already provided by its base class.

class Shape {
    area() {
        return 0;
    }
}

class Circle extends Shape {
    radius: number;

    constructor(radius: number) {
        super();
        this.radius = radius;
    }

    area() {
        return Math.PI * this.radius * this.radius;
    }
}

const circle = new Circle(5);
console.log(circle.area()); 

4. Best Practices for Using TypeScript Classes

Keep Classes Small and Focused

A class should have a single responsibility. If a class is doing too many things, it becomes difficult to maintain and test. For example, a class that is responsible for both user authentication and order processing should be split into two separate classes.

Use Interfaces for Contracts

Interfaces in TypeScript can be used to define a contract that a class must follow. This makes the code more modular and easier to understand.

interface Printable {
    print(): void;
}

class Document implements Printable {
    print() {
        console.log("Printing the document...");
    }
}

Conclusion

In conclusion, TypeScript does have classes, and they are a powerful feature that allows developers to write organized, reusable, and maintainable code. By understanding the fundamental concepts, usage methods, common practices, and best practices, developers can make the most of classes in TypeScript. Whether it’s creating simple objects or building complex object - oriented systems, classes in TypeScript provide a solid foundation.

References