add a protected property to a class in typescript

To add a protected property to a class in TypeScript, we need to use the protected access modifier in TypeScript. A protected property or method can be accessed within the class and its subclasses but not outside of the class.

Consider the example below:

index.ts
class Person {
    protected age: number;

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

    public describe(): void {
        console.log(`I am ${this.age} years old`);
    }
}

class Student extends Person {
    private grade: string;

    constructor(age: number, grade: string) {
        super(age);
        this.grade = grade;
    }

    public describe(): void {
        console.log(`I am ${this.age} years old and I am in grade ${this.grade}`);
    }
}

let john: Person = new Person(30);
let jane: Student = new Student(13, '7th');

john.describe(); // I am 30 years old
jane.describe(); // I am 13 years old and I am in grade 7th
655 chars
31 lines

In the example above, we have defined a Person class with a protected age property. We have also defined a Student class that extends the Person class and has a private grade property. Both classes have a describe method that logs a description to the console. Notice that the Student class is able to access the age property of the Person class because it is protected.

By using the protected access modifier, we can restrict access to certain properties or methods of a class and ensure that they are only accessible within the class and its subclasses.

gistlibby LogSnag