TypeScript Classes

This chapter delves into TypeScript classes, a cornerstone of object-oriented programming (OOP). Classes in TypeScript extend the JavaScript class syntax with powerful features like type annotations, access modifiers, and interfaces, enabling developers to create robust, maintainable, and scalable applications.

Chapter Goal

  • To understand what classes are and their role in TypeScript.
  • To learn how to define and use classes effectively.
  • To explore advanced class features such as inheritance, access modifiers, and static members.

Key Characteristics for TypeScript Classes

  • Blueprint for Objects: Defines reusable structures and behaviors for objects.
  • Encapsulation: Groups properties and methods within a single unit.
  • Type Safety: Adds type annotations to properties, methods, and constructors.
  • Inheritance: Allows one class to inherit properties and methods from another.
  • Advanced Features: Supports interfaces, abstract classes, and decorators.

Basic Rules for TypeScript Classes

  1. Use the class keyword to define a class.
  2. Annotate class properties and methods with types for better safety.
  3. Use constructors to initialize object properties.
  4. Leverage extends for inheritance and implements for interfaces.
  5. Encapsulate implementation details with access modifiers (private, protected, public).

Best Practices

  1. Use meaningful class names that describe their purpose.
  2. Keep methods short and focused on a single responsibility.
  3. Document complex class behaviors for better maintainability.
  4. Prefer composition over inheritance for flexible design.
  5. Avoid overloading classes with too many responsibilities (follow the Single Responsibility Principle).

Syntax Table

Serial No Component Syntax Example Description
1 Basic Class class Person { name: string; constructor(name: string) { this.name = name; } } Declares a simple class with a constructor.
2 Access Modifiers class Employee { private id: number; protected salary: number; public name: string; } Controls visibility of properties and methods.
3 Inheritance class Manager extends Employee { role: string; } Enables a class to inherit from another class.
4 Static Members class MathUtil { static PI = 3.14; static add(a: number, b: number): number { return a + b; } } Defines members accessible without instantiating the class.
5 Abstract Classes abstract class Shape { abstract area(): number; } Declares a class meant to be extended, not instantiated.

Syntax Explanation

1. Basic Class

What is a Basic Class

A template for creating objects, containing properties and methods.

Syntax

class Person {

  name: string;

 

  constructor(name: string) {

    this.name = name;

  }

 

  greet(): void {

    console.log(`Hello, my name is ${this.name}.`);

  }

}

Detailed Explanation

  • The Person class has a property name and a method greet.
  • The constructor initializes the name property when a new object is created.

Example

const person = new Person(‘Alice’);

person.greet(); // Output: Hello, my name is Alice.

Output

Hello, my name is Alice.

Notes

  • Basic classes serve as the foundation for OOP in TypeScript.

Warnings

  • Always initialize properties to avoid undefined values.

2. Access Modifiers

What are Access Modifiers

Keywords that control the visibility of class members.

Syntax

class Employee {

  private id: number;

  protected salary: number;

  public name: string;

 

  constructor(id: number, name: string, salary: number) {

    this.id = id;

    this.name = name;

    this.salary = salary;

  }

}

Detailed Explanation

  • private members are accessible only within the class.
  • protected members are accessible within the class and its subclasses.
  • public members are accessible from anywhere.

Example

class Manager extends Employee {

  getSalary(): number {

    return this.salary; // Accessible because it’s protected.

  }

}

 

const manager = new Manager(1, ‘Bob’, 50000);

console.log(manager.name); // Output: Bob

Output

Bob

Notes

  • Use access modifiers to enforce encapsulation and data hiding.

Warnings

  • Avoid overexposing properties with public unless necessary.

3. Inheritance

What is Inheritance

A mechanism where one class inherits properties and methods from another class.

Syntax

class Manager extends Employee {

  department: string;

 

  constructor(id: number, name: string, salary: number, department: string) {

    super(id, name, salary);

    this.department = department;

  }

}

Detailed Explanation

  • The extends keyword allows Manager to inherit from Employee.
  • The super keyword calls the constructor of the parent class.

Example

const manager = new Manager(1, ‘Alice’, 80000, ‘IT’);

console.log(manager.department); // Output: IT

Output

IT

Notes

  • Inheritance promotes code reuse and establishes hierarchical relationships.

Warnings

  • Avoid deep inheritance chains, as they can lead to complexity.

4. Static Members

What are Static Members

Class-level properties and methods that do not require object instantiation.

Syntax

class MathUtil {

  static PI: number = 3.14;

 

  static add(a: number, b: number): number {

    return a + b;

  }

}

Detailed Explanation

  • static members belong to the class rather than any specific instance.
  • They are accessed using the class name.

Example

console.log(MathUtil.PI); // Output: 3.14

console.log(MathUtil.add(10, 20)); // Output: 30

Output

3.14

30

Notes

  • Static members are ideal for utility functions and constants.

Warnings

  • Static members cannot access non-static members directly.

5. Abstract Classes

What are Abstract Classes

Classes that cannot be instantiated and must be extended by other classes.

Syntax

abstract class Shape {

  abstract area(): number;

}

 

class Circle extends Shape {

  radius: number;

 

  constructor(radius: number) {

    super();

    this.radius = radius;

  }

 

  area(): number {

    return Math.PI * this.radius * this.radius;

  }

}

Detailed Explanation

  • Abstract classes define methods without implementation.
  • Subclasses must implement abstract methods.

Example

const circle = new Circle(5);

console.log(circle.area()); // Output: 78.53981633974483

Output

78.53981633974483

Notes

  • Use abstract classes for defining common interfaces and enforcing implementation.

Warnings

  • Avoid using abstract classes when a simple interface suffices.

Real-Life Project

Project Name

Employee Management System

Project Goal

Demonstrates how to use classes to model employees, managers, and departments in an organization.

Code for This Project

class Employee {

  id: number;

  name: string;

  salary: number;




  constructor(id: number, name: string, salary: number) {

    this.id = id;

    this.name = name;

    this.salary = salary;

  }




  display(): void {

    console.log(`ID: ${this.id}, Name: ${this.name}, Salary: ${this.salary}`);

  }

}




class Manager extends Employee {

  department: string;




  constructor(id: number, name: string, salary: number, department: string) {

    super(id, name, salary);

    this.department = department;

  }




  display(): void {

    super.display();

    console.log(`Department: ${this.department}`);

  }

}




const emp = new Employee(101, 'John Doe', 50000);

emp.display();




const mgr = new Manager(102, 'Jane Smith', 75000, 'HR');

mgr.display();

Save and Run

  1. Save the code into a file named employeeManagement.ts.
  2. Compile the TypeScript file using the TypeScript Compiler (e.g., run tsc employeeManagement.ts in your terminal).
  3. Execute the compiled JavaScript file with Node.js (e.g., node employeeManagement.js).