📘 TypeScript
TypeScript Classes and Object-Oriented Programming
Basic Class
class Person {
name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): string {
return `Hi, I am ${this.name}`;
}
getAge(): number {
return this.age;
}
}
const alice = new Person("Alice", 25);
console.log(alice.greet()); // Hi, I am Alice
console.log(alice.getAge()); // 25
Constructor Shorthand
class Point {
constructor(
public x: number,
public y: number,
private label: string = "point"
) {}
toString(): string {
return `${this.label}(${this.x}, ${this.y})`;
}
}
const p = new Point(3, 4);
console.log(p.toString()); // point(3, 4)
Inheritance
class Animal {
constructor(public name: string) {}
speak(): string { return "..."; }
}
class Dog extends Animal {
constructor(name: string, public breed: string) {
super(name);
}
speak(): string { return `${this.name} barks!`; }
}
const rex = new Dog("Rex", "Labrador");
console.log(rex.speak()); // Rex barks!
Implementing Interfaces
interface Serializable {
toJSON(): string;
fromJSON(json: string): void;
}
class Config implements Serializable {
private data: Record = {};
toJSON(): string {
return JSON.stringify(this.data);
}
fromJSON(json: string): void {
this.data = JSON.parse(json);
}
}
Abstract Classes
abstract class Shape {
abstract area(): number;
describe(): string {
return `This shape has area ${this.area().toFixed(2)}`;
}
}
class Circle extends Shape {
constructor(private radius: number) { super(); }
area(): number { return Math.PI * this.radius ** 2; }
}
const c = new Circle(5);
console.log(c.describe()); // This shape has area 78.54