15 minlesson

Classes in TypeScript

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

typescript
1class Package {
2 // Properties with types
3 id: string;
4 weight: number;
5 fragile: boolean;
6
7 // Constructor
8 constructor(id: string, weight: number, fragile: boolean = false) {
9 this.id = id;
10 this.weight = weight;
11 this.fragile = fragile;
12 }
13
14 // Method
15 getShippingCost(): number {
16 const baseRate = this.weight * 2.5;
17 return this.fragile ? baseRate * 1.5 : baseRate;
18 }
19}
20
21const 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:

typescript
1// Verbose way
2class Package {
3 id: string;
4 weight: number;
5
6 constructor(id: string, weight: number) {
7 this.id = id;
8 this.weight = weight;
9 }
10}
11
12// Shorthand with parameter properties
13class Package {
14 constructor(
15 public id: string,
16 public weight: number,
17 public fragile: boolean = false
18 ) {}
19}
20
21// Same result, less boilerplate!

Readonly Properties

Properties that can't be changed after initialization:

typescript
1class Shipment {
2 readonly id: string;
3 readonly createdAt: Date;
4 status: string;
5
6 constructor(id: string) {
7 this.id = id;
8 this.createdAt = new Date();
9 this.status = 'pending';
10 }
11
12 updateStatus(newStatus: string): void {
13 this.status = newStatus; // OK
14 // this.id = 'new-id'; // Error: readonly
15 }
16}

Getters and Setters

Computed properties with controlled access:

typescript
1class Rectangle {
2 constructor(
3 private _width: number,
4 private _height: number
5 ) {}
6
7 // Getter
8 get area(): number {
9 return this._width * this._height;
10 }
11
12 // Getter and setter
13 get width(): number {
14 return this._width;
15 }
16
17 set width(value: number) {
18 if (value <= 0) {
19 throw new Error('Width must be positive');
20 }
21 this._width = value;
22 }
23}
24
25const rect = new Rectangle(10, 5);
26console.log(rect.area); // 50 (accessed like property)
27rect.width = 20; // Calls setter
28// rect.width = -5; // Throws error

Static Members

Properties and methods on the class itself:

typescript
1class ShippingRates {
2 static readonly BASE_RATE = 5.99;
3 static readonly PRIORITY_MULTIPLIER = 2.0;
4
5 static calculatePriority(weight: number): number {
6 return weight * ShippingRates.BASE_RATE * ShippingRates.PRIORITY_MULTIPLIER;
7 }
8}
9
10// Access without instantiation
11console.log(ShippingRates.BASE_RATE); // 5.99
12console.log(ShippingRates.calculatePriority(10)); // 119.8

Implementing Interfaces

Classes can implement interfaces to guarantee structure:

typescript
1interface Trackable {
2 trackingNumber: string;
3 getStatus(): string;
4}
5
6interface Weighable {
7 weight: number;
8 getShippingCost(): number;
9}
10
11class TrackedPackage implements Trackable, Weighable {
12 constructor(
13 public trackingNumber: string,
14 public weight: number,
15 private status: string = 'pending'
16 ) {}
17
18 getStatus(): string {
19 return this.status;
20 }
21
22 getShippingCost(): number {
23 return this.weight * 2.5;
24 }
25}

Class Expressions

Classes can be assigned to variables (useful for factories):

typescript
1const PackageClass = class {
2 constructor(public id: string) {}
3};
4
5const pkg = new PackageClass('PKG001');
6
7// Factory returning class
8function createPackageClass(prefix: string) {
9 return class {
10 id: string;
11 constructor(num: number) {
12 this.id = `${prefix}-${num}`;
13 }
14 };
15}
16
17const USPSPackage = createPackageClass('USPS');
18const pkg2 = new USPSPackage(123); // id: 'USPS-123'

Summary

FeaturePurpose
ConstructorInitialize object state
Parameter propertiesShorthand for declaration + initialization
readonlyImmutable properties
Getters/SettersComputed/validated properties
staticClass-level members
implementsGuarantee interface compliance

Next: Access modifiers for encapsulation.