TS Classes

TypeScript Classes

TypeScript adds robust Object-Oriented Programming features to JavaScript classes.

It introduces data access modifiers like public, private, and protected.

This allows you to securely encapsulate data and hide sensitive internal logic.

Classes are heavily used in major enterprise frameworks like Angular and NestJS.


1. Defining a Class

Defining a class in TypeScript is very similar to standard ES6 JavaScript.

The major difference is that you must declare the types of the class properties upfront.

This guarantees the class is instantiated with perfectly valid data every time.

Basic Class Example:

class Person {
  name: string;
  

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

const akash = new Person("Akash");

console.log("Person created:", akash.name);


2. Access Modifiers

Modifiers control whether a property can be accessed from outside the class instance.

public (default) allows access from anywhere, inside or outside.

private completely restricts access to only within the class itself.

Modifiers Example:

class BankAccount {
  private balance: number; // Hidden from the outside
  

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

public getBalance(): number { return this.balance; // Safe controlled access } }

const myAccount = new BankAccount(1000); console.log("Balance:", myAccount.getBalance());


3. SEO and Structure

Well-structured Object-Oriented code is highly modular and extremely easy to test.

Fewer bugs in production directly correlates to better site uptime and SEO ranking.

Implementing interfaces ensures your classes adhere strictly to defined architectural contracts.

Implements Example:

interface Shape {
  getArea(): number;
}

class Square implements Shape { constructor(public width: number) {} getArea() { return this.width * this.width; } }

const mySquare = new Square(5); console.log("Square Area:", mySquare.getArea());


Exercise

?

Which modifier restricts property access strictly to within the class itself?


4. Final Thoughts

Classes bring traditional software engineering principles directly into the JavaScript ecosystem.

They are phenomenal for organizing large amounts of complex business logic.

Next, we will explore the immense power of TypeScript Generics!