Classes in TypeScript
Classes are the building blocks of many design patterns. TypeScript adds type safety and access control to JavaScript classes.
Basic Class Structure
typescript1class Package {2 // Properties with types3 id: string;4 weight: number;5 fragile: boolean;67 // Constructor8 constructor(id: string, weight: number, fragile: boolean = false) {9 this.id = id;10 this.weight = weight;11 this.fragile = fragile;12 }1314 // Method15 getShippingCost(): number {16 const baseRate = this.weight * 2.5;17 return this.fragile ? baseRate * 1.5 : baseRate;18 }19}2021const pkg = new Package('PKG001', 10, true);22console.log(pkg.getShippingCost()); // 37.5
Parameter Properties Shorthand
TypeScript allows declaring and initializing properties directly in the constructor:
typescript1// Verbose way2class Package {3 id: string;4 weight: number;56 constructor(id: string, weight: number) {7 this.id = id;8 this.weight = weight;9 }10}1112// Shorthand with parameter properties13class Package {14 constructor(15 public id: string,16 public weight: number,17 public fragile: boolean = false18 ) {}19}2021// Same result, less boilerplate!
Readonly Properties
Properties that can't be changed after initialization:
typescript1class Shipment {2 readonly id: string;3 readonly createdAt: Date;4 status: string;56 constructor(id: string) {7 this.id = id;8 this.createdAt = new Date();9 this.status = 'pending';10 }1112 updateStatus(newStatus: string): void {13 this.status = newStatus; // OK14 // this.id = 'new-id'; // Error: readonly15 }16}
Getters and Setters
Computed properties with controlled access:
typescript1class Rectangle {2 constructor(3 private _width: number,4 private _height: number5 ) {}67 // Getter8 get area(): number {9 return this._width * this._height;10 }1112 // Getter and setter13 get width(): number {14 return this._width;15 }1617 set width(value: number) {18 if (value <= 0) {19 throw new Error('Width must be positive');20 }21 this._width = value;22 }23}2425const rect = new Rectangle(10, 5);26console.log(rect.area); // 50 (accessed like property)27rect.width = 20; // Calls setter28// rect.width = -5; // Throws error
Static Members
Properties and methods on the class itself:
typescript1class ShippingRates {2 static readonly BASE_RATE = 5.99;3 static readonly PRIORITY_MULTIPLIER = 2.0;45 static calculatePriority(weight: number): number {6 return weight * ShippingRates.BASE_RATE * ShippingRates.PRIORITY_MULTIPLIER;7 }8}910// Access without instantiation11console.log(ShippingRates.BASE_RATE); // 5.9912console.log(ShippingRates.calculatePriority(10)); // 119.8
Implementing Interfaces
Classes can implement interfaces to guarantee structure:
typescript1interface Trackable {2 trackingNumber: string;3 getStatus(): string;4}56interface Weighable {7 weight: number;8 getShippingCost(): number;9}1011class TrackedPackage implements Trackable, Weighable {12 constructor(13 public trackingNumber: string,14 public weight: number,15 private status: string = 'pending'16 ) {}1718 getStatus(): string {19 return this.status;20 }2122 getShippingCost(): number {23 return this.weight * 2.5;24 }25}
Class Expressions
Classes can be assigned to variables (useful for factories):
typescript1const PackageClass = class {2 constructor(public id: string) {}3};45const pkg = new PackageClass('PKG001');67// Factory returning class8function createPackageClass(prefix: string) {9 return class {10 id: string;11 constructor(num: number) {12 this.id = `${prefix}-${num}`;13 }14 };15}1617const USPSPackage = createPackageClass('USPS');18const pkg2 = new USPSPackage(123); // id: 'USPS-123'
Summary
| Feature | Purpose |
|---|---|
| Constructor | Initialize object state |
| Parameter properties | Shorthand for declaration + initialization |
| readonly | Immutable properties |
| Getters/Setters | Computed/validated properties |
| static | Class-level members |
| implements | Guarantee interface compliance |
Next: Access modifiers for encapsulation.