Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TypeScript Access Modifiers

TypeScript Access Modifiers

Access modifiers (Access Modifiers) are one of the core features of TypeScript object-oriented programming.

They are used to control the visibility of class members (properties, methods, constructors).

With access modifiers, you can achieve encapsulation and protect the internal implementation details of a class.


Access modifier scope public Inside the class ✓ Subclass ✓ Outside ✓ protected Inside the class ✓ Subclass ✓ Outside ✗ private Inside the class ✓ Subclass ✗ Outside ✗ Use Cases public Public methods/properties e.g., user name, login method protected Methods visible to subclasses e.g., calculation formulas, template methods private Internal implementation details e.g., database connections, internal calculations

Why access modifiers are needed

Encapsulation is one of the three major principles of object-oriented programming.

Encapsulation means hiding data and the methods that operate on it, exposing only the necessary interfaces to the outside.

Access modifiers are the means to achieve encapsulation; they control the visibility scope of class members.

Concept explanation:Access modifiers determine where class members can be accessed. TypeScript provides three access modifiers: public, protected, private.


The public modifier

public is the default access modifier, meaning members can be accessed anywhere.

Whether inside the class, in a subclass, or outside the class, public members can be accessed.

Example

// Define the Animal class

class

Animal

{

   

// Use public to modify the name property (can be omitted, since it is public by default)

    public name

:

string

;

   

// Constructor

    public constructor

(

name

:

string

)

{

       

this

.

name

=

name

;

   

}

   

// A public speak method

    public speak

(

)

:

void

{

        console.

log

(

this

.

name

" makes a sound"

)

;

   

}

}

// Create an instance

var

animal

=

new

Animal

(

"Animal"

)

;

// Access a public property from outside the class

console.

log

(

animal.

name

)

;

// Call a public method from outside the class

animal.

speak

(

)

;

Running result:

动物

动物 发出声音

Explanation:If no access modifier is written, TypeScript uses public by default. Therefore public can be omitted, but for code clarity, it is recommended to declare it explicitly.


The private modifier

private means a private member, which can only be accessed inside the class where it is defined.

Neither subclasses nor the outside of the class can access private members.

This is commonly used to hide a class's internal implementation details and protect data from accidental modification.

Example

// Define the BankAccount class

class

BankAccount

{

   

// Use private to modify the balance, which can only be accessed inside the class

    private balance

:

number

;

   

// Constructor

    constructor

(

initialBalance

:

number

)

{

       

this

.

balance

=

initialBalance

;

   

}

   

// Deposit method

    public deposit

(

amount

:

number

)

:

void

{

       

if

(

amount

0

)

{

           

this

.

balance

+=

amount

;

 

// The class can access private properties internally

            console.

log

(

"Deposit successful, current balance: "

this

.

balance

)

;

       

}

   

}

   

// Get the balance

    public getBalance

(

)

:

number

{

       

return

this

.

balance

;

 

// The class can access private properties internally

   

}

}

// Create an account instance

var

account

=

new

BankAccount

(

1000

)

;

// Deposit

account.

deposit

(

500

)

;

// Get the balance through a public method

console.

log

(

"Balance: "

account.

getBalance

(

)

)

;

// Error: private properties cannot be accessed directly from outside the class

// console.log(account.balance); // Compilation error!

Running result:

存款成功,当前余额: 1500

余额: 1500

Best practices:Setting a class's internal state to private and providing controlled access through public methods is the standard way to achieve encapsulation.


The protected modifier

protected means a protected member, which can be accessed inside the class and in subclasses.

The outside of the class cannot access protected members directly.

This is very useful when you want subclasses to inherit certain features of the parent class while hiding implementation details.

Example

// Define the Person base class

class

Person

{

   

// Use protected to modify name so subclasses can access it

    protected name

:

string

;

    constructor

(

name

:

string

)

{

       

this

.

name

=

name

;

   

}

}

// Define the Employee class, inheriting from Person

class

Employee

extends

Person

{

   

// The department is private

    private department

:

string

;

    constructor

(

name

:

string

,

department

:

string

)

{

       

super

(

name

)

;

 

// Call the parent class constructor

       

this

.

department

=

department

;

   

}

   

// Self-introduction method

    public introduce

(

)

:

string

{

       

// The subclass can access the protected member name

       

return

"I am "

this

.

name

", working in "

this

.

department

" department"

;

   

}

}

// Create an Employee instance

var

emp

=

new

Employee

(

"Alice"

,

"Engineering Department"

)

;

console.

log

(

emp.

introduce

(

)

)

;

// Error: protected members cannot be accessed from outside the class

// console.log(emp.name); // Compilation error!

Running result:

我是 Alice,在 技术部 工作

Application scenarios:protected is commonly used to define properties that subclasses need to use but that should not be exposed to the outside.


The readonly modifier

readonly is used to make a property read-only.

It can only be assigned at declaration or in the constructor, and cannot be modified afterward.

This is very useful when defining constants or identifiers.

Example

// Define the User class

class

User

{

   

// Properties modified with readonly can only be assigned during initialization

   

// The user ID

    readonly id

:

number

;

   

// Username

    readonly name

:

string

;

    constructor

(

id

:

number

,

name

:

string

)

{

       

this

.

id

=

id

;

       

this

.

name

=

name

;

   

}

}

// Create a User instance

var

user

=

new

User

(

1

,

"Alice"

)

;

console.

log

(

"User: "

user.

id

", "

user.

name

)

;

// Error: readonly properties cannot be modified

// user.id = 2; // Compilation error!

// user.name = "Bob"; // Compilation error!

Running result:

用户: 1, Alice

Note:readonly and private do not conflict. You can use both together, so a property can neither be modified nor accessed from outside.


Parameter properties

TypeScript provides a shorthand syntax for parameter properties (Parameter Properties).

You can use access modifiers directly on constructor parameters to automatically create and initialize properties.

Example

// Define the Point class

class

Point

{

   

// Use modifiers directly on constructor parameters

   

// Equivalent to declaring a property and assigning it at the same time

    constructor

(

       

// public modifier: create a public property x

        public x

:

number

,

       

// public modifier: create a public property y

        public y

:

number

,

       

// private modifier: create a private property z

        private z

:

number

   

)

{

       

// The constructor body can be empty, since the properties are created automatically

   

}

   

// Calculate the sum of the three dimensions

    public sum

(

)

:

number

{

       

// All properties can be accessed inside the class

       

return

this

.

x

this

.

y

this

.

z

;

   

}

}

// Create a Point instance

var

point

=

new

Point

(

1

,

2

,

3

)

;

// Public properties can be accessed from outside

console.

log

(

"x: "

point.

x

)

;

console.

log

(

"y: "

point.

y

)

;

// Invoke methods

console.

log

(

"Sum: "

point.

sum

(

)

)

;

// Error: private properties cannot be accessed from outside

// console.log(point.z); // Compilation error!

Running result:

x: 1

y: 2

总和: 6

Simplified code:Parameter properties can greatly simplify class definitions, avoiding repetitive declaration and assignment code.


Comparison of access modifiers

The following is a comparison of the scope of the three access modifiers.

Modifiers Inside the class Subclass Outside the class (instance)
public ✓ Accessible ✓ Accessible ✓ Accessible
protected ✓ Accessible ✓ Accessible ✗ Not accessible
private ✓ Accessible ✗ Not accessible ✗ Not accessible

Selection advice:Use private by default, protected when subclasses need access, and public when full exposure is needed.


Notes

Best practices:Use the strictest access modifier possible. Expose only necessary public interfaces and set internal implementations to private or protected.


Summary

Access modifiers are a core tool for achieving encapsulation in TypeScript.

Note:Make a habit of using access modifiers; this is the foundation of writing high-quality TypeScript code.