3 TypeScript Access Modifiers

3 TypeScript Access Modifiers

Table of contents

TypeScript access modifiers change the visibility and accessibility of methods and properties of a class. TypeScript decides the scope of property or method by applying restrictions on them. TypeScript controls the access logically at compile time, not at runtime.

TypeScript offers three access modifiers:

  • public

  • protected

  • private

TypeScript Access Modifiers

public

The properties and methods declared public are accessible in all locations. public is the default access modifier, so if a property or method does not have any access modifiers, it will take the public by default. You do not need to write public on any class member, but it will help the readability and style of your code.

class Person {
   public firstName: string;
   public lastName: string; 
   ssn: string ; 
}

protected

The protected modifier allows properties and methods to be accessible within the class and its subclasses.

class Person {
   public firstName: string; 
   public lastName: string;
   protected ssn: string;
   protected address: string;
}

private

The private modifier limits the visibility of properties and methods to the same class only.

class Person {
    private firstName: string;
    private lastName: string;
    private ssn: string;
    private address: string;

    constructor(firstName: string, lastName: string, ssn: string, address:      string) 
{
        this.firstName = firstName;
        this.lastName = lastName;
        this.ssn = ssn ;
        this.address = address;
    }

    getFullName(): string {
        return `${this.firstName} ${this.lastName}`; 
    }
}