TypeScript - Public, Private, Protected and Readonly Modifiers Example

This tutorial shows how to use public, private, protected and readonly modifiers in TypeScript with examples.

Public, private, and protected modifiers

Understanding public

In TypeScript, each member is public by default. You may still mark a member public explicitly. 
For example:
class Employee {
    public id: number;
    public firstName: string;
    public lastName: string;

    constructor(id: number, firstName: string, lastName: string) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public getFullName() {
        return this.firstName + ' ' + this.lastName;
    }
}

// create Employee class object
let employee = new Employee(100, 'Ramesh', 'Fadatare');
console.log(employee);
console.log(employee.getFullName());
Output:
Employee { id: 100, firstName: 'Ramesh', lastName: 'Fadatare' }
Ramesh Fadatare
After compiling, the above TypeScript code produces below JavaScript code:
var Employee = /** @class */ (function () {
    function Employee(id, firstName, lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }
    Employee.prototype.getFullName = function () {
        return this.firstName + ' ' + this.lastName;
    };
    return Employee;
}());
// create Employee class object
var employee = new Employee(100, 'Ramesh', 'Fadatare');
console.log(employee);
console.log(employee.getFullName())

Understanding private

When a member is marked private, it cannot be accessed from outside of its containing class. For example:
class Employee {
    private id: number;
    public firstName: string;
    public lastName: string;

    public getFullName() {
        return this.firstName + ' ' + this.lastName;
    }
}

// create Employee class object
let employee = new Employee();
employee.id = 100; // Property 'id' is private and only accessible within class 'Employee'.ts
employee.firstName = 'Ramesh';

console.log(employee);
console.log(employee.getFullName());
Above code gives below compilation error:
Property 'id' is private and only accessible within class 'Employee'.ts

Understanding protected

The protected modifier acts much like the private modifier with the exception that members declared protected can also be accessed within deriving classes. For example,
class Person {
    protected name: string;
    constructor(name: string) {
        this.name = name;
    }
}

class Employee extends Person {
    private department: string;

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

    public getElevatorPitch() {
        return `Hello, my name is ${this.name} and I work in ${this.department}.`;
    }
}

let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name); // Property 'name' is protected and only 
                          // accessible within class 'Person' and its subclasses.
Notice that while we can’t use name from outside of Person, we can still use it from within an instance method of Employee because Employee derives from Person. Above code gives below compilation error:
Property 'name' is protected and only accessible within class 'Person' and its subclasses.
A constructor may also be marked protected. This means that the class cannot be instantiated outside of its containing class, but can be extended. 
For example,
class Person {
    protected name: string;
    protected constructor(theName: string) { this.name = theName; }
}

// Employee can extend Person
class Employee extends Person {
    private department: string;

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

    public getElevatorPitch() {
        return `Hello, my name is ${this.name} and I work in ${this.department}.`;
    }
}

let howard = new Employee("Howard", "Sales");
let john = new Person("John"); // Error: The 'Person' constructor is protected

Understanding readonly modifier

You can make properties readonly by using the readonly keyword. Readonly properties must be initialized at their declaration or in the constructor. 
For Example:
class Employee{
    readonly id: number;
    public firstName: string;
    readonly lastName: string;

    constructor(id: number, firstName: string, lastName: string){
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public getFullName(){
        return this.firstName + ' ' + this.lastName;
    }
}

// create Employee class object
let employee = new Employee(100, 'Ramesh', 'Fadatare');
employee.id = 200; // Error: Cannot assign to 'id' because it is a read-only property.
employee.lastName = 'Kapoor'; // Error: Cannot assign to 'lastName' because it is a read-only property
console.log(employee);
console.log(employee.getFullName());
Notice that the above code gives below compilation error:
employee.id = 200; // Error: Cannot assign to 'id' because it is a read-only property.
employee.lastName = 'Kapoor'; // Error: Cannot assign to 'lastName' because it is a read-only property
Learn more about TypeScript at TypeScript Tutorial with Examples.

Comments