Ts Classes in TypeScript
Classes in TypeScript provide a way to create reusable, object-oriented code. They bring the structure of traditional object-oriented programming (OOP) to JavaScript with features like inheritance, encapsulation, and abstraction.
Defining a Class
Here’s a basic example:
const person = new Person("Alice", 30);person.greet(); // "Hello, my name is Alice and I am 30 years old."
Key Features of TypeScript Classes
1. Class Properties
- Properties can be explicitly defined with types.
- Default values can be assigned.
class Product { name: string = "Default Product"; price: number = 0;}
2. Constructor
- A special method used to initialize object properties.
class Car { make: string; model: string; constructor(make: string, model: string) { class Animal { public species: string; private weight: number; constructor(species: string, weight: number) { console.log(tiger.getWeight()); // 200
4. Readonly Properties
Properties that can only be set during initialization.
class Book { readonly title: string; constructor(title: string) { class MathUtils { static PI: number = 3.14; static calculateCircumference(radius: number): number { return 2 * MathUtils.PI * radius; }}console.log(MathUtils.calculateCircumference(5)); // 31.4
Inheritance
Classes can inherit from other classes using the extends keyword.
class Employee { name: string; constructor(name: string) { abstract class Shape { abstract getArea(): number; describe(): void { console.log("This is a shape."); }}class Circle extends Shape { radius: number; constructor(radius: number) { interface Flyable { fly(): void;}class Bird implements Flyable { fly(): void { console.log("The bird is flying."); }}
Class Example: Real-World Use Case
A Simple Banking System:
class BankAccount { private balance: number; constructor(private accountHolder: string, initialBalance: number) { class Point { constructor(public x: number, public y: number) {}}class User { constructor(public name: string, public age?: number) {}}const user = new User("Alice");console.log(user.age); // undefined
Index Signatures
Allow defining dynamic properties.
class Dictionary { [key: string]: string;}const dict = new Dictionary();dict["hello"] = "world";