private
- TypeScript course
- Intermediate
- Lesson 7/89
- 4 min
Learn class-internal members with private.
What is private?
private indicates that a member is accessible only inside the class itself. Trying to access it from outside causes a compile error. This is the core tool for encapsulation.
class Account {
private balance: number;
constructor(balance: number) {
this.balance = balance;
}
getBalance(): number {
return this.balance;
}
}
const a = new Account(100);
// a.balance; // error
console.log(a.getBalance());Encapsulation
With private you hide internal state; from outside it is only accessed via methods. This preserves consistency inside the class and prevents external code from making direct changes.
class Account {
private balance: number = 0;
deposit(amount: number): void {
this.balance += amount;
}
}Practice Account class with a private field
Define an Account class with a private balance: number field. Add a constructor that takes balance and assigns it with this. Write a getBalance(): number method that returns this.balance. Create a new Account(100) and call getBalance().
Starter code
// Account sınıfı tanımla (gizli bakiye alanı)
// constructor ile balance al
// getBalance metodu bakiyeyi döndürür
// yeni Account oluştur, getBalance çağırSample solution
class Account {
private balance: number;
constructor(balance: number) {
this.balance = balance;
}
getBalance(): number {
return this.balance;
}
}
const a = new Account(100);
console.log(a.getBalance());Expected output
100
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if you try to access a private field from outside the class?
- Runtime error
- Returns undefined
- Compile error Correct answer
- It works
Explanation: Accessing a private field from outside the class causes a compile error. This enforces encapsulation at compile time; it does not wait until runtime.
2 Complete the private modifier
class Account {
____ balance: number = 0;
}
class Account {
private balance: number = 0;
}
Explanation: You write private because you want the balance field to be accessible only inside the class. public opens it to outside, protected to subclasses, and static moves it to the class level.
3 private parts
| Term | Meaning |
|---|---|
private |
Accessible only inside the class |
this.balance |
Access from inside the class |
a.balance |
External access (error) |
getBalance() |
Public accessor method |