TypeScript - Access Modifiers: Your Friendly Guide to Code Privacy

Hello there, future coding superstar! ? I'm thrilled to be your guide on this exciting journey through TypeScript's access modifiers. As someone who's been teaching programming for years, I can tell you that understanding these concepts is like learning the secret handshakes of the coding world. So, let's dive in and uncover these mysteries together!

TypeScript - Access Modifiers

What Are Access Modifiers?

Before we jump into the specifics, let's chat about what access modifiers are. Imagine you're building a super cool treehouse (that's our code!). Access modifiers are like the rules you set for who can climb up, who can peek inside, and who gets to use the secret compartments. They help us control how parts of our code can be accessed and used.

In TypeScript, we have three main access modifiers:

Modifier Description
public Accessible from anywhere
private Only accessible within the same class
protected Accessible within the class and its subclasses

Now, let's explore each of these in detail!

Public Access Modifier

The public modifier is like leaving your treehouse door wide open. Anyone can come in, use the swing, or borrow your comic books. In code terms, this means any part of your program can access and use these elements.

Here's a fun example:

class Superhero {
    public name: string;
    public power: string;

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

    public usePower() {
        console.log(`${this.name} uses ${this.power}!`);
    }
}

const spiderman = new Superhero("Spider-Man", "web-slinging");
console.log(spiderman.name); // Outputs: Spider-Man
spiderman.usePower(); // Outputs: Spider-Man uses web-slinging!

In this example, name, power, and usePower() are all public. We can access and use them from anywhere in our code. It's like Spider-Man swinging freely through the city!

Private Access Modifiers

Now, let's talk about private. This is like having a secret diary in your treehouse that only you can read. In TypeScript, private members can only be accessed within the same class.

Let's update our Superhero class:

class Superhero {
    public name: string;
    private secretIdentity: string;

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

    private changeClothes() {
        console.log("Quick change in a phone booth!");
    }

    public goOnMission() {
        this.changeClothes();
        console.log(`${this.name} is ready for action!`);
    }
}

const superman = new Superhero("Superman", "Clark Kent");
console.log(superman.name); // Outputs: Superman
// console.log(superman.secretIdentity); // Error! secretIdentity is private
// superman.changeClothes(); // Error! changeClothes() is private
superman.goOnMission(); // This works! Outputs: Quick change in a phone booth! Superman is ready for action!

See how we can't access secretIdentity or call changeClothes() directly? That's the power of private! It keeps Superman's secrets safe.

Protected Access Modifiers

Last but not least, we have protected. Think of this as a special treehouse rule that applies to you and your siblings, but not to the neighborhood kids. In TypeScript, protected members are accessible within the class and its subclasses.

Let's create a Superhero family:

class Superhero {
    public name: string;
    protected superpower: string;

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

    protected useSuperpowerInternal() {
        console.log(`Using ${this.superpower} internally`);
    }
}

class Sidekick extends Superhero {
    public useSuperheroPower() {
        console.log(`${this.name} borrows power: ${this.superpower}`);
        this.useSuperpowerInternal();
    }
}

const batman = new Superhero("Batman", "gadgets");
const robin = new Sidekick("Robin", "acrobatics");

// console.log(batman.superpower); // Error! superpower is protected
// batman.useSuperpowerInternal(); // Error! useSuperpowerInternal() is protected

robin.useSuperheroPower(); // This works! Outputs: Robin borrows power: acrobatics Using acrobatics internally

Here, Sidekick can access the protected members of Superhero, but we can't access them directly from outside the classes.

Wrapping Up

And there you have it, my coding apprentices! We've explored the secret world of TypeScript access modifiers. Remember:

  1. public is for everyone (like a public park)
  2. private is just for the class itself (like your personal diary)
  3. protected is for the class and its children (like family secrets)

Using these modifiers wisely will help you create more secure, organized, and maintainable code. It's like being a superhero of the programming world – you know when to share your powers and when to keep them under wraps!

As you practice with these concepts, imagine you're designing your own superhero team. Who gets to know what? How do you keep the balance between teamwork and secret identities? That's the fun of programming – you get to make these exciting decisions!

Keep coding, keep learning, and remember: with great power comes great responsibility... and really cool TypeScript classes! ??‍♂️?‍♀️

Credits: Image by storyset