📘 TypeScript
Классы TypeScript и объектно-ориентированное программирование
Базовый класс
class Person {
name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): string {
return `Привет, я ${this.name}`;
}
getAge(): number {
return this.age;
}
}
const alice = new Person("Алиса", 25);
console.log(alice.greet()); // Привет, я Алиса
console.log(alice.getAge()); // 25
Сокращённый конструктор
class Point {
constructor(
public x: number,
public y: number,
private label: string = "точка"
) {}
toString(): string {
return `${this.label}(${this.x}, ${this.y})`;
}
}
const p = new Point(3, 4);
console.log(p.toString()); // точка(3, 4)
Наследование
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} лает!`; }
}
const rex = new Dog("Рекс", "Лабрадор");
console.log(rex.speak()); // Рекс лает!
Реализация интерфейсов
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 class Shape {
abstract area(): number;
describe(): string {
return `Фигура с площадью ${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()); // Фигура с площадью 78.54