Class Fundamentals

Loading concept...

๐Ÿ—๏ธ TypeScript Classes: Building Your Own Toy Factory!

Imagine you want to build the same toy car over and over again. Instead of making each one from scratch, you create a blueprint - a set of instructions that tells you exactly what pieces to use and how to put them together. Thatโ€™s exactly what a Class is in TypeScript!


๐ŸŽฏ What is a Class?

A Class is like a cookie cutter. The cookie cutter is the class, and each cookie you make is an object (also called an instance).

class Dog {
  name: string;
  age: number;
}

Here, Dog is our blueprint. Every dog we create will have a name and an age.


๐Ÿ“ฆ Class Properties: The Things Your Object Has

Properties are like the pockets in your backpack. They hold stuff!

class Backpack {
  color: string;
  zippers: number;
  isEmpty: boolean;
}

Each backpack has:

  • A color (like โ€œblueโ€ or โ€œredโ€)
  • A number of zippers
  • A true/false for isEmpty

๐ŸŒŸ Giving Properties Starting Values

You can set default values right away:

class GameCharacter {
  health: number = 100;
  coins: number = 0;
  level: number = 1;
}

Every new character starts with 100 health, 0 coins, and level 1!


๐Ÿ› ๏ธ Class Methods: The Things Your Object Can Do

Methods are like buttons on a remote control. Press a button, something happens!

class Robot {
  batteryLevel: number = 100;

  sayHello() {
    console.log("Beep boop! Hello!");
  }

  dance() {
    console.log("*does robot dance*");
    this.batteryLevel -= 10;
  }
}

Our robot can sayHello() and dance(). Dancing uses battery!

Using Methods

const myRobot = new Robot();
myRobot.sayHello();  // "Beep boop! Hello!"
myRobot.dance();     // "*does robot dance*"

๐Ÿญ Constructor: The Birth Certificate

The constructor is a special method that runs when you create a new object. Itโ€™s like filling out a form for a new baby - you write down the name, birthday, etc.

class Pet {
  name: string;
  species: string;
  age: number;

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

const fluffy = new Pet("Fluffy", "cat", 3);

When we write new Pet("Fluffy", "cat", 3), the constructor catches those values and saves them!

๐Ÿ’ก Shortcut: Parameter Properties

TypeScript has a magic shortcut:

class Pet {
  constructor(
    public name: string,
    public species: string,
    public age: number
  ) {}
}

Adding public before each parameter automatically creates and assigns the property. Same result, less typing!


๐Ÿ” Access Modifiers: Who Can Touch What?

Imagine a treasure chest with different locks:

graph TD A[๐Ÿ”“ public] --> B[Anyone can open] C[๐Ÿ”’ private] --> D[Only the owner can open] E[๐Ÿ”‘ protected] --> F[Owner and family can open]

public - Everyone Welcome! ๐Ÿ”“

class Playground {
  public swings: number = 4;
}

const park = new Playground();
console.log(park.swings); // โœ… Works!

private - Secret! Shh! ๐Ÿ”’

class Diary {
  private secrets: string[] = [];

  addSecret(secret: string) {
    this.secrets.push(secret);
  }
}

const myDiary = new Diary();
myDiary.addSecret("I like pizza");
// myDiary.secrets โŒ Error! Can't peek!

Only methods inside the Diary class can read secrets.

protected - Family Only ๐Ÿ”‘

class Animal {
  protected sound: string = "...";

  makeSound() {
    console.log(this.sound);
  }
}

class Cat extends Animal {
  constructor() {
    super();
    this.sound = "Meow!"; // โœ… Works!
  }
}

protected means the class AND its children (subclasses) can use it.


๐Ÿ” Private Fields: The JavaScript Way

TypeScript also supports JavaScriptโ€™s # syntax for truly private fields:

class BankAccount {
  #balance: number = 0;

  deposit(amount: number) {
    this.#balance += amount;
  }

  getBalance() {
    return this.#balance;
  }
}

const account = new BankAccount();
account.deposit(100);
// account.#balance โŒ Truly hidden!
console.log(account.getBalance()); // 100

๐Ÿค” private vs #private - Whatโ€™s the Difference?

Feature private keyword # private field
Checked at Compile time Runtime
In JavaScript Disappears Still private
Can be tricked With type casting Never

Use # when you need bulletproof privacy!


๐Ÿ“– readonly: Look, Donโ€™t Touch!

readonly means โ€œyou can look at this, but you canโ€™t change it after itโ€™s set.โ€

class Certificate {
  readonly studentName: string;
  readonly issueDate: Date;

  constructor(name: string) {
    this.studentName = name;
    this.issueDate = new Date();
  }
}

const cert = new Certificate("Alex");
// cert.studentName = "Bob"; โŒ Error!
console.log(cert.studentName); // โœ… "Alex"

Think of it like a trophy with your name engraved. You can show it off, but you canโ€™t change the engraving!

๐ŸŽฏ readonly + Access Modifiers

You can combine them:

class Config {
  public readonly appName: string = "MyApp";
  private readonly secretKey: string;

  constructor(key: string) {
    this.secretKey = key;
  }
}

๐ŸŽญ The this Type: Knowing Yourself

Inside a class, this refers to โ€œme, myself, this object.โ€

class Counter {
  count: number = 0;

  increment(): this {
    this.count++;
    return this;
  }

  decrement(): this {
    this.count--;
    return this;
  }
}

const counter = new Counter();
counter.increment().increment().decrement();
console.log(counter.count); // 1

Returning this lets you chain methods together like train cars!

๐Ÿ”ฎ Why this Type Matters

When you extend a class, returning this type keeps things working:

class BasicBuilder {
  reset(): this {
    console.log("Reset!");
    return this;
  }
}

class FancyBuilder extends BasicBuilder {
  addSparkles(): this {
    console.log("โœจ Sparkles added!");
    return this;
  }
}

const builder = new FancyBuilder();
builder.reset().addSparkles(); // Both work!

If reset() returned BasicBuilder instead of this, the chain would break!


๐ŸŽจ Putting It All Together: A Complete Example

class Superhero {
  public readonly name: string;
  private #secretIdentity: string;
  protected powerLevel: number = 50;

  constructor(
    name: string,
    secretIdentity: string
  ) {
    this.name = name;
    this.#secretIdentity = secretIdentity;
  }

  usePower(): this {
    console.log(`${this.name} uses power!`);
    this.powerLevel -= 10;
    return this;
  }

  rest(): this {
    this.powerLevel += 20;
    console.log("Feeling refreshed!");
    return this;
  }

  getStatus(): string {
    return `${this.name}: ${this.powerLevel}%`;
  }
}

const hero = new Superhero(
  "Captain TypeScript",
  "Tim Script"
);

hero.usePower().usePower().rest();
console.log(hero.getStatus());
// "Captain TypeScript: 50%"

๐Ÿง  Quick Recap

Concept What It Does Example
Class Blueprint for objects class Dog {}
Properties Data the object holds name: string
Methods Actions the object can do bark() {}
Constructor Sets up new objects constructor() {}
public Anyone can access Default behavior
private Only class can access private secret
protected Class + children access protected data
#field True private (runtime) #password
readonly Canโ€™t be changed readonly id
this type Enables method chaining return this

๐Ÿš€ You Did It!

You now know how to:

  • Create blueprints (classes) for your objects
  • Give them properties (stuff they have)
  • Give them methods (stuff they can do)
  • Control who can access what
  • Make unchangeable values with readonly
  • Chain methods with this

Classes are like superpowers for organizing your code. Now go build something amazing! ๐ŸŽ‰

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.