How to Use the ‘Protected’ Modifier in TypeScript

Updated: January 7, 2024 By: Guest Contributor Post a comment

Introduction

TypeScript, that fine offspring of JavaScript, bequeaths us with the treasures of static typing and class features. Among these gifts is the ‘protected’ modifier, a sentinel guarding the gates between public access and private sanctity. This tutorial shall embolden thee to wield ‘protected’ with grace and might.

Understanding ‘protected’

Mark these words wisely, as I unravel the mysteries of the ‘protected’ modifier in the land of TypeScript. At its core, ‘protected’ is akin to declaring, “This member shall be accessible to all descendants but hidden from strangers.” It’s akin to family lore, known to kin but a riddle to the outsider.

class Base {
    protected secretMethod(): void {
        console.log('This is a protected method.');
    }
}

class Derived extends Base {
    public revealSecret(): void {
        this.secretMethod(); // Look here! It's accessible within a subclass.
    }
}

class Stranger {
    private attemptAccess(base: Base): void {
        // base.secretMethod(); // Alas, this is forbidden!
    }
}

Protected Properties

As we delve deeper into the realms of TypeScript, witness how ‘protected’ guards not just methods, but properties as well. Notice below how siblings share secrets, whilst to the world such treasures are veiled.

class Parent {
    protected familyHeirloom: string = 'Secret Potion';
}

class Child extends Parent {
    public boastHeirloom(): void {
        console.log(`In my possession is the ${this.familyHeirloom}!`);
    }
}

// Meanwhile, outside the family line...
class Outsider {
    public tryToPeek(parent: Parent): void {
        // console.log(parent.familyHeirloom); // Tis' not for prying eyes!
    }
}

Conclusion

By now, ye are well-equipped to journey forth with the ‘protected’ modifier as your trusted squire in TypeScript. Use this power to craft classes that shrewdly expose their internals to chosen heirs while keeping interlopers well at bay. So venture on, brave coder, and may your objects encapsulate with the wisdom of a land time-tested.