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.
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.
class Person {
name: string;
constructor(n: string) {
this.name = n;
}
}
const akash = new Person("Akash");
console.log("Person created:", akash.name);
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.
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());
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.
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());
Which modifier restricts property access strictly to within the class itself?
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!