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:
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.
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 likename: stringbut don't give it a value in the constructor, TypeScript will throw an error. It saves you fromundefinedbugs 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.
public(Default): Accessible from anywhere (inside the class, outside the class, inheriting classes).private: Accessible only inside the class where it is defined.protected: Accessible inside the class and by classes that extend it (children), but not from the outside.
Code Example
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 #:
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?
- Declare
name. - Accept
namein constructor. - 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:
- Declares the property.
- Accepts the argument.
- Assigns the argument to the property.
All in one line! ⚡
Code Example
The Long Way:
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):
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: PrivateThis 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
// 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.
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
- Classes are blueprints for objects.
- Constructors initialize the object.
- Public/Private/Protected control who can touch your data.
- Parameter Properties (
constructor(public x: string)) cut down boilerplate code significantly. - 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:
Define an
IAuthInterface:- 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.
- This interface should define two methods:
Create a
UserBase Class:- This class should have two
protectedproperties:userId(string) andusername(string). - The constructor should accept and initialize these two properties.
- This class should have two
Create a
UserProfileClass:- This class must inherit from the
Userclass and implement theIAuthinterface. - Its constructor must use parameter properties to declare and initialize two
publicproperties:email(string) and areadonlycreationDate(Date). - The constructor should also accept the
userId,username, and an initialpassword(string) to satisfy the parent class and internal requirements. - Declare a
privateproperty namedpasswordHashof typestring. This property should be initialized within the constructor with the providedpasswordvalue. - Implement the
loginandresetPasswordmethods as defined by theIAuthinterface. Theloginmethod should compare its argument against theprivate passwordHash, andresetPasswordshould update it.
- This class must inherit from the
Expected result
Your final code should be a single TypeScript block containing three definitions:
- An
interfacenamedIAuthwith the specifiedloginandresetPasswordmethod signatures. - A
classnamedUserwith a constructor that initializes itsprotectedpropertiesuserIdandusername. - A
classnamedUserProfilethat correctly uses theextendsandimplementskeywords.- Its constructor signature should use
publicandpublic readonlyparameter properties foremailandcreationDate. - It must call the parent
super()constructor with the correct arguments. - It must contain a
privatepropertypasswordHash. - It must provide concrete implementations for the
loginandresetPasswordmethods.
- Its constructor signature should use