public, private, protected

Access modifiers that control where a class’s fields and methods can be used from.

On this page

Example

#
TypeScript
class Wallet {
  private balance = 0

  constructor(public readonly owner: string) {}

  add(gems: number): void {
    this.balance += gems
  }

  get total(): number {
    return this.balance
  }
}

const wallet = new Wallet('Emma')
wallet.add(50)
wallet.add(20)
console.log(wallet.owner, wallet.total)
Result
Emma 70

Definition and usage

#

Class fields and methods are public (public) by default, meaning accessible from anywhere. private restricts access to inside the class, and protected to the class and its derived classes.

TypeScript’s modifiers work at compile time. After compiling to JavaScript, a private field is an ordinary property. If you need real privacy in the running program, use JavaScript’s native # fields.

The “parameter properties” shorthand lets you declare and assign a field in one place: constructor(private name: string) {} creates a private field name with the argument’s value.

Syntax

#
Syntax
class Name {
  public a: type
  private b: type
  protected c: type
}

More examples

#
Trying to access a private field
TypeScript
wallet.balance = 1000
// Error: Property 'balance' is private and only accessible within class 'Wallet'.

Good practices

#
  • For data that truly shouldn’t be accessible from the outside, use # fields, which also work after compilation.
  • The constructor(private x: T) shorthand saves you from repeating the declaration and the assignment.

Related entries

#

Spotted a mistake or missing an example? Write to us.