Advanced Class Features

Loading concept...

🏰 TypeScript’s Advanced Class Features: Building Your Kingdom

Imagine you’re building a magical kingdom. Every castle needs special rooms, secret passages, and royal rules. TypeScript’s advanced class features are like the blueprints for creating the most amazing castles ever!


🗝️ The Story Begins

You’re the Royal Architect of the TypeScript Kingdom. Your job? Build magnificent castles (classes) with special powers. Let’s discover each magical feature, one by one!


1. 📊 Static Members: The Kingdom’s Shared Treasures

What Are They?

Imagine your kingdom has one giant treasure chest that EVERYONE can use—not just one person. That’s what static members are!

Regular members = Each person has their own lunchbox Static members = One cafeteria everyone shares

Simple Example

class Kingdom {
  static kingdomName = "TypeScript Land";
  static population = 0;

  name: string;

  constructor(name: string) {
    this.name = name;
    Kingdom.population++; // Everyone adds to the same count!
  }

  static getInfo() {
    return `${Kingdom.kingdomName} has ${Kingdom.population} citizens`;
  }
}

// Use static without creating an object!
console.log(Kingdom.kingdomName); // "TypeScript Land"

const citizen1 = new Kingdom("Alice");
const citizen2 = new Kingdom("Bob");

console.log(Kingdom.getInfo()); // "TypeScript Land has 2 citizens"

🎯 Key Point

  • Access with ClassName.staticMember—no new needed!
  • Perfect for counters, config settings, or utility functions

2. 🚪 Getters and Setters: The Royal Gatekeepers

What Are They?

Think of a castle gate with guards. You can’t just walk in—you have to check in! Getters and setters are like those guards.

  • Getter = “Show me what’s inside!” (reads data)
  • Setter = “I want to change something!” (writes data, but checks first)

Simple Example

class Dragon {
  private _age = 0;

  // Getter - reads the age
  get age(): number {
    return this._age;
  }

  // Setter - protects the age from bad values
  set age(value: number) {
    if (value < 0) {
      console.log("Dragons can't have negative age!");
      return;
    }
    this._age = value;
  }
}

const spike = new Dragon();
spike.age = 100;  // Uses setter âś…
console.log(spike.age);  // Uses getter → 100

spike.age = -5;  // "Dragons can't have negative age!" ⚠️

🎯 Key Point

  • Use getters/setters to protect your data
  • They look like regular properties but have superpowers!

3. ⚡ Parameter Properties: The Shortcut Spell

What Is It?

Tired of writing the same thing twice? Parameter properties are a magic spell that creates AND assigns properties in one line!

The Old Way (Long)

class Knight {
  name: string;
  level: number;

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

The New Way (Parameter Properties)

class Knight {
  constructor(
    public name: string,
    public level: number
  ) {
    // That's it! No extra code needed!
  }
}

const arthur = new Knight("Arthur", 50);
console.log(arthur.name);  // "Arthur"
console.log(arthur.level); // 50

🎯 Key Point

  • Add public, private, protected, or readonly before parameter
  • TypeScript does the boring work for you!

4. 👨‍👩‍👧 Class Inheritance: The Family Tree

What Is It?

Just like you inherit eye color from your parents, classes can inherit features from other classes!

  • Parent class = The original (also called “base” or “superclass”)
  • Child class = Gets parent’s stuff + adds its own (also called “derived”)

Simple Example

// Parent class
class Animal {
  constructor(public name: string) {}

  speak() {
    console.log(`${this.name} makes a sound`);
  }
}

// Child class - extends means "I'm part of this family"
class Dog extends Animal {
  breed: string;

  constructor(name: string, breed: string) {
    super(name);  // Call parent's constructor first!
    this.breed = breed;
  }

  fetch() {
    console.log(`${this.name} fetches the ball! 🎾`);
  }
}

const buddy = new Dog("Buddy", "Golden Retriever");
buddy.speak();  // "Buddy makes a sound" (from parent)
buddy.fetch();  // "Buddy fetches the ball! 🎾" (own method)

🎯 Key Point

  • Use extends to inherit
  • Always call super() in child constructor first!

5. 📜 Implementing Interfaces: The Royal Contract

What Is It?

An interface is like a contract or promise. When a class “implements” an interface, it promises to have certain features.

Think of a job application: “Must have: name, email, experience”

Simple Example

// The contract
interface Flyable {
  wingSpan: number;
  fly(): void;
}

// This class promises to follow the contract
class Bird implements Flyable {
  wingSpan: number;

  constructor(wingSpan: number) {
    this.wingSpan = wingSpan;
  }

  fly() {
    console.log("Flapping wings and soaring! 🦅");
  }
}

// A class can implement MULTIPLE interfaces!
interface Swimmable {
  dive(): void;
}

class Duck implements Flyable, Swimmable {
  wingSpan = 60;

  fly() { console.log("Duck flying! 🦆"); }
  dive() { console.log("Duck diving! đź’¦"); }
}

🎯 Key Point

  • implements = “I promise to have all these things”
  • If you forget something, TypeScript yells at you! (helpful errors)

6. 🔄 The Override Keyword: Rewriting the Rules

What Is It?

When a child class wants to change how a parent’s method works, it “overrides” it. The override keyword makes this super clear!

Simple Example

class Vehicle {
  start() {
    console.log("Starting vehicle...");
  }
}

class ElectricCar extends Vehicle {
  override start() {
    console.log("Silently powering up... 🔋⚡");
  }
}

const tesla = new ElectricCar();
tesla.start();  // "Silently powering up... 🔋⚡"

Why Use override?

class Vehicle {
  start() { }
}

class Car extends Vehicle {
  override startt() { }  // ❌ TYPO! TypeScript catches it!
  // Error: This method does not override anything
}

🎯 Key Point

  • override = “I’m intentionally replacing the parent’s version”
  • Catches typos and mistakes—your safety net!

7. 🏛️ Abstract Classes: The Unfinished Blueprint

What Is It?

An abstract class is like a blueprint that says “Here’s the plan, but YOU fill in the details.”

It’s like a coloring book—the outlines are there, but you add the colors!

Key Rules

  • ❌ Can’t create objects from abstract classes directly
  • âś… Must be extended by another class
  • âś… Can have normal methods AND abstract methods

Simple Example

abstract class Shape {
  color: string;

  constructor(color: string) {
    this.color = color;
  }

  // Normal method - works as-is
  describe() {
    console.log(`This is a ${this.color} shape`);
  }

  // Abstract method - child MUST implement this!
  abstract calculateArea(): number;
}

// ❌ This won't work:
// const shape = new Shape("red"); // Error!

// âś… This works - child fills in the blanks
class Circle extends Shape {
  constructor(color: string, public radius: number) {
    super(color);
  }

  calculateArea(): number {
    return Math.PI * this.radius * this.radius;
  }
}

const myCircle = new Circle("blue", 5);
myCircle.describe();  // "This is a blue shape"
console.log(myCircle.calculateArea());  // 78.54...

8. 🎭 Abstract Methods: The “You Must Do This” Rule

What Is It?

Abstract methods are promises that say: “Any child class MUST create this method!”

Like a recipe that says “Add your favorite topping”—you MUST add something!

Simple Example

abstract class PaymentProcessor {
  // Abstract = YOU must write this code
  abstract processPayment(amount: number): boolean;

  // Regular method - I'll handle this
  logTransaction(amount: number) {
    console.log(`Processing $${amount}...`);
  }
}

class CreditCardProcessor extends PaymentProcessor {
  // MUST implement this or TypeScript yells!
  processPayment(amount: number): boolean {
    console.log(`Charging credit card: $${amount} đź’ł`);
    return true;
  }
}

class CryptoProcessor extends PaymentProcessor {
  // Each child can implement differently!
  processPayment(amount: number): boolean {
    console.log(`Sending crypto: $${amount} ₿`);
    return true;
  }
}

🎯 Key Point

  • Abstract methods have no body (no { } code)
  • Child classes MUST provide the implementation

🗺️ The Big Picture

graph LR A[Class Features] --> B[Static Members] A --> C[Getters/Setters] A --> D[Parameter Properties] A --> E[Inheritance] A --> F[Interfaces] A --> G[Override] A --> H[Abstract Classes] B --> B1[Shared by all instances] C --> C1[Control access to data] D --> D1[Shortcut for properties] E --> E1[extends parent class] F --> F1[implements contract] G --> G1[Replace parent method] H --> H1[Blueprint with blanks]

🎯 Quick Comparison Chart

Feature What It Does Keyword
Static Members Shared across all instances static
Getters/Setters Control property access get / set
Parameter Properties Auto-create properties public/private in constructor
Inheritance Reuse parent’s code extends
Interfaces Enforce a contract implements
Override Replace parent’s method override
Abstract Class Unfinished blueprint abstract class
Abstract Method Must-implement method abstract methodName()

🚀 You Did It!

You’ve just learned the 8 superpowers of TypeScript classes:

  1. Static = Kingdom’s shared treasure
  2. Getters/Setters = Castle guards
  3. Parameter Properties = Magic shortcut spell
  4. Inheritance = Family tree
  5. Interfaces = Royal contracts
  6. Override = Rewriting the rules
  7. Abstract Classes = Coloring book outlines
  8. Abstract Methods = “You must fill this in!”

Now go build your TypeScript kingdom! 🏰✨

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.