Classes: Object-Oriented TypeScript

7 min read

Welcome back, developer! 🚀

Today we are stepping into the "Architecture" phase of TypeScript. Up until now, we’ve mostly been dealing with types, shapes, and functions. But as your applications grow from a single file script into a massive enterprise monster, you need a blueprint. You need structure. You need Classes.

If you come from a functional programming background, don't run away! TypeScript classes are just syntactic sugar over JavaScript prototypes, but with the superpower of strict typing. They allow us to create objects that hold data (state) and behavior (methods) in a tidy, reusable package.

Let’s build some blueprints! 🏗️


1. Class Fundamentals and Constructors

The Problem

In standard JavaScript, we often create objects using object literals:

typescript
const car1 = { make: "Toyota", model: "Corolla", drive: () => console.log("Vroom") };
const car2 = { make: "Honda", model: "Civic", drive: () => console.log("Vroom") };

This works fine for two cars. But what if you are building a traffic simulation with 10,000 cars? Copy-pasting objects is prone to typos, and if you change the structure of one, you break consistency.

The Solution

A Class acts as a template/blueprint. It ensures every object created from it looks and behaves the same way.

How it works in TypeScript

In TypeScript, there is a specific nuance compared to vanilla JS: You must declare your properties upfront.

If you try to assign this.speed = 0 in the constructor without declaring speed as a field first, TypeScript will yell at you. This ensures the shape of the class is known statically.

Code Example

Let's build a Spaceship.

typescript
class Spaceship {
  // 1. Property Declarations (State)
  // In TS, these define the "Shape" of the class instance.
  name: string;
  fuel: number;
  
  // 2. The Constructor
  // This runs immediately when you create a new instance (new Spaceship).
  constructor(name: string, startingFuel: number) {
    this.name = name;
    this.fuel = startingFuel;
  }

  // 3. Methods (Behavior)
  fly(distance: number): void {
    if (this.fuel >= distance) {
      this.fuel -= distance;
      console.log(`${this.name} traveled ${distance} lightyears.`);
    } else {
      console.log("Not enough fuel!");
    }
  }
}

// Usage
const falcon = new Spaceship("Millennium Falcon", 100);
falcon.fly(12); // Output: Millennium Falcon traveled 12 lightyears.

💡 Under the Hood: When this compiles to older JavaScript (ES5), this class becomes a function, and the methods are attached to the prototype. It’s not magic; it’s just very organized prototype delegation.

Industry Standard Note: TypeScript has a setting called strictPropertyInitialization. If you declare a property like name: string but don't give it a value in the constructor, TypeScript will throw an error. It saves you from undefined bugs later!


2. Access Modifiers: public, private, and protected

The Problem

Imagine you have a BankAccount class. If anyone can do myAccount.balance = 1000000, your bank goes bankrupt. You need to hide internal state and only allow changes through specific methods (like deposit() or withdraw()). This is called Encapsulation.

The Solution

TypeScript provides three keywords to control who can see or change your properties.

  1. public (Default): Accessible from anywhere (inside the class, outside the class, inheriting classes).
  2. private: Accessible only inside the class where it is defined.
  3. protected: Accessible inside the class and by classes that extend it (children), but not from the outside.

Code Example

typescript
class BankVault {
  public bankName: string;       // Everyone can know the bank's name
  protected securityGuard: string; // Only the bank and its branches know the guard
  private vaultCode: number;     // ONLY this specific Vault class knows the code

  constructor(name: string, guard: string, code: number) {
    this.bankName = name;
    this.securityGuard = guard;
    this.vaultCode = code;
  }

  // Public method exposes controlled access
  public unlock(attempt: number): boolean {
    // We can access private 'vaultCode' here because we are inside the class
    return attempt === this.vaultCode;
  }
}

const myVault = new BankVault("Iron Bank", "Gregor", 1234);

console.log(myVault.bankName); // ✅ OK: "Iron Bank"

// console.log(myVault.securityGuard); 
// ❌ Error: Property 'securityGuard' is protected and only accessible within class 'BankVault' and its subclasses.

// console.log(myVault.vaultCode); 
// ❌ Error: Property 'vaultCode' is private and only accessible within class 'BankVault'.

// usage via method
myVault.unlock(1234); // ✅ OK

🧠 Interesting Fact: The "Soft" Privacy

TypeScript's private keyword is "soft." It only checks usage during compile time. Once your code is converted to JavaScript, the private keyword is erased, and technically, a determined hacker could access myVault.vaultCode in the browser console.

If you need hard runtime privacy, use the modern JavaScript hash syntax #:

typescript
class ModernVault {
  #hardPrivateCode: number; // This stays private even in runtime JS!
}

Most industry codebases still use TS private for convenience unless they specifically need security against runtime tampering.


3. Shorthand Initialization: Parameter Properties

The Problem

Look at our Spaceship class again. Notice the repetition?

  1. Declare name.
  2. Accept name in constructor.
  3. Assign this.name = name.

If you have a class with 10 properties, writing this out is tedious. Developers are efficiently lazy; we hate boilerplate.

The Solution

Parameter Properties. By adding an access modifier (public, private, protected, or readonly) directly to the constructor arguments, TypeScript automatically:

  1. Declares the property.
  2. Accepts the argument.
  3. Assigns the argument to the property.

All in one line! ⚡

Code Example

The Long Way:

typescript
class Player {
  public name: string;
  private health: number;

  constructor(name: string, health: number) {
    this.name = name;
    this.health = health;
  }
}

The Shorthand Way (Preferred Industry Pattern):

typescript
class Player {
  // No declarations needed up here!
  
  constructor(
    public name: string, 
    private health: number
  ) {
    // No 'this.name = name' needed here!
    // It is done automatically.
  }
}

const p1 = new Player("Mario", 100);
console.log(p1.name); // "Mario"
// console.log(p1.health); // Error: Private

This drastically reduces line count and is very common in frameworks like Angular or NestJS.


4. Implementing Interfaces in Classes

The Problem

You are working on a game with different entities: Human, Robot, and Alien. They all move differently and have different internal structures, but you want to ensure they all have a move() method so your game engine can treat them the same way.

Inheritance (extends) connects classes by what they are. Interfaces connect classes by what they do.

The Solution

The implements keyword. This forces a class to adhere to a specific contract (Interface). If the class forgets to implement a property or method from the interface, TypeScript throws an error.

Code Example

typescript
// 1. Define the Contract
interface Movable {
  speed: number;
  move(): void;
}

// 2. Implement the Contract
class Car implements Movable {
  // We MUST have speed
  constructor(public speed: number) {}

  // We MUST have move()
  move() {
    console.log(`Driving at ${this.speed} mph`);
  }
}

class Horse implements Movable {
  constructor(public speed: number) {}

  move() {
    console.log(`Galloping at ${this.speed} mph`);
  }
  
  // We can add extra stuff not in the interface
  eatCarrot() {
    console.log("Cronch");
  }
}

// ❌ Error Example
// class Rock implements Movable { 
//    // Error: Class 'Rock' incorrectly implements interface 'Movable'.
//    // Property 'speed' is missing...
// }

🧐 Detail: Multiple Interfaces

A class can implement multiple interfaces, allowing for flexible composition.

typescript
class SmartPhone implements Phone, Computer, Camera { ... }

This is often preferred over deep inheritance chains (like class SmartPhone extends Electronics extends Device...) because it avoids the "Banana-Gorilla-Jungle" problem: You wanted a banana (a method), but you got the gorilla holding it and the entire jungle (parent class baggage).


📚 Resources & References


🎯 Summary

  1. Classes are blueprints for objects.
  2. Constructors initialize the object.
  3. Public/Private/Protected control who can touch your data.
  4. Parameter Properties (constructor(public x: string)) cut down boilerplate code significantly.
  5. Implements ensures a class follows a specific structure/interface.

Go forth and architect your systems! 🏛️

Challenge

Challenge: Build a Secure User Profile System

Your task is to model a secure user profile system using TypeScript's class features. You will need to define an authentication contract, create a base user class, and then build a concrete profile class that implements the contract and extends the base class, ensuring proper data encapsulation.

Requirements:

  1. Define an IAuth Interface:

    • This interface should define two methods:
      • login(password: string): boolean: A method to verify a password.
      • resetPassword(newPassword: string): void: A method to update the user's password.
  2. Create a User Base Class:

    • This class should have two protected properties: userId (string) and username (string).
    • The constructor should accept and initialize these two properties.
  3. Create a UserProfile Class:

    • This class must inherit from the User class and implement the IAuth interface.
    • Its constructor must use parameter properties to declare and initialize two public properties: email (string) and a readonly creationDate (Date).
    • The constructor should also accept the userId, username, and an initial password (string) to satisfy the parent class and internal requirements.
    • Declare a private property named passwordHash of type string. This property should be initialized within the constructor with the provided password value.
    • Implement the login and resetPassword methods as defined by the IAuth interface. The login method should compare its argument against the private passwordHash, and resetPassword should update it.

Expected result

Your final code should be a single TypeScript block containing three definitions:

  1. An interface named IAuth with the specified login and resetPassword method signatures.
  2. A class named User with a constructor that initializes its protected properties userId and username.
  3. A class named UserProfile that correctly uses the extends and implements keywords.
    • Its constructor signature should use public and public readonly parameter properties for email and creationDate.
    • It must call the parent super() constructor with the correct arguments.
    • It must contain a private property passwordHash.
    • It must provide concrete implementations for the login and resetPassword methods.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.