๐๏ธ 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! ๐