class Person {// Properties name:string; age:number;// Constructorconstructor(name:string, age:number) {this.name= name;this.age= age; }// Methodgreet():string {return`Hello, I'm ${this.name}`; }}// Usageconst person =newPerson("Alice",30);
12.2 Access Modifiers
class Employee {public name:string;// Accessible everywhere (default)private salary:number;// Only within classprotected id:number;// Within class and subclassesreadonly ssn:string;// Can't be modified after initializationconstructor(name:string, salary:number, id:number, ssn:string) {this.name= name;this.salary= salary;this.id= id;this.ssn= ssn; }}
// Instead of this verbose approach:class Car { make:string; model:string; year:number;constructor(make:string, model:string, year:number) {this.make= make;this.model= model;this.year= year; }}// Use parameter properties (very handy!):class Car {constructor(public make:string,public model:string,private year:number ) {}// Properties are automatically created and assigned!}
12.3 Inheritance
class Animal {constructor(public name:string) {}move(distance:number=0):void {console.log(`${this.name} moved ${distance}m`); }}class Dog extends Animal {constructor(name:string,public breed:string) {super(name);// Must call super() before using 'this' }bark():void {console.log("Woof! Woof!"); }// Override parent methodmove(distance:number=5):void {console.log("Running...");super.move(distance);// Call parent implementation }}
Animal
↑
extends
|
Dog
12.4 Abstract Classes
abstractclass Shape {abstractarea():number;// Must be implemented by subclassesabstractperimeter():number;// Can have concrete methodsdescribe():string {return`Area: ${this.area()}, Perimeter: ${this.perimeter()}`; }}class Rectangle extends Shape {constructor(private width:number,private height:number) {super(); }area():number {returnthis.width*this.height; }perimeter():number {return2* (this.width+this.height); }}// const shape = new Shape(); // Error! Can't instantiate abstract classconst rect =newRectangle(10,20);// OK
12.5 Static Members
class MathUtils {staticPI=3.14159;staticcalculateCircleArea(radius:number):number {return MathUtils.PI* radius * radius; }}// Access without instantiationconsole.log(MathUtils.PI);console.log(MathUtils.calculateCircleArea(5));
classPoint {constructor(public x:number,public y:number) {}}// Using class as a typelet point:Point;point =newPoint(10,20);// OK// Classes create two things:// 1. Constructor function// 2. Type for instances