TypeScript Essentials
TypeScript Classes
TypeScript Classes
Section titled “TypeScript Classes”TypeScript enhances JavaScript classes with type annotations and access modifiers.
Basic Class
Section titled “Basic Class”class Person { name: string; age: number;
constructor(name: string, age: number) { this.name = name; this.age = age; }
greet(): string { return `Hello, I'm ${this.name}`; }}
const person = new Person("Alice", 25);Access Modifiers
Section titled “Access Modifiers”class User { public name: string; // Accessible anywhere private password: string; // Only in this class protected email: string; // This class and subclasses
constructor(name: string, password: string, email: string) { this.name = name; this.password = password; this.email = email; }}Parameter Properties
Section titled “Parameter Properties”// Shorthand syntaxclass User { constructor( public name: string, private password: string, readonly id: number ) {}}Getters and Setters
Section titled “Getters and Setters”class Circle { private _radius: number;
constructor(radius: number) { this._radius = radius; }
get radius(): number { return this._radius; }
set radius(value: number) { if (value < 0) throw new Error("Radius must be positive"); this._radius = value; }
get area(): number { return Math.PI * this._radius ** 2; }}Inheritance
Section titled “Inheritance”class Animal { constructor(public name: string) {}
speak(): void { console.log(`${this.name} makes a sound`); }}
class Dog extends Animal { constructor(name: string, public breed: string) { super(name); }
speak(): void { console.log(`${this.name} barks`); }}Abstract Classes
Section titled “Abstract Classes”abstract class Shape { abstract area(): number; abstract perimeter(): number;
describe(): string { return `Area: ${this.area()}, Perimeter: ${this.perimeter()}`; }}
class Rectangle extends Shape { constructor(public width: number, public height: number) { super(); }
area(): number { return this.width * this.height; }
perimeter(): number { return 2 * (this.width + this.height); }}Implementing Interfaces
Section titled “Implementing Interfaces”interface Printable { print(): void;}
class Document implements Printable { constructor(public content: string) {}
print(): void { console.log(this.content); }}