본문 바로가기
language/typescript

🔐 접근 제한자 & readonly – 클래스 멤버 보호하기

by 죄니안죄니 2025. 4. 27.
🏗️ 타입스크립트 중급 시리즈 – 클래스와 OOP 패턴
🟢 ① 클래스와 인터페이스의 관계 | 🔵 ② private / protected / public / readonly | ⚪ ③ 추상 클래스 vs 인터페이스 | ⚪ ④ 데코레이터 기초 (NestJS 활용)

🔐 접근 제한자 & readonly – 클래스 멤버 보호하기

객체지향 프로그래밍의 중요한 원칙 중 하나는 캡슐화(Encapsulation)입니다.
타입스크립트에서도 클래스 멤버에 대한 접근을 제어할 수 있는 키워드가 존재하며, 정보 은닉과 API의 안정성을 위한 핵심 기능입니다.


① public – 어디서든 접근 가능 (기본값)

class User {
  public name: string;

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

const user = new User('철수');
console.log(user.name); // ✅ 접근 가능

public은 기본값이기 때문에 생략해도 됩니다.
→ 클래스 외부에서도 자유롭게 접근할 수 있습니다.


② private – 클래스 내부에서만 접근 가능

class Account {
  private balance: number = 0;

  deposit(amount: number) {
    this.balance += amount;
  }

  getBalance(): number {
    return this.balance;
  }
}

const acc = new Account();
acc.deposit(1000);
console.log(acc.getBalance()); // ✅

console.log(acc.balance); // ❌ Error: 'balance' is private

private 멤버는 **클래스 외부에서 절대 접근할 수 없습니다.**


③ protected – 상속받은 클래스에서는 접근 가능

class Animal {
  protected sound: string = '...';

  makeSound() {
    console.log(this.sound);
  }
}

class Dog extends Animal {
  bark() {
    this.sound = '멍멍'; // ✅ 접근 가능
  }
}

const dog = new Dog();
dog.makeSound(); // 멍멍
// dog.sound ❌ 에러: protected 멤버는 외부 접근 불가

protected는 클래스 외부에서는 막고, 상속 관계에서는 허용합니다.


④ readonly – 읽기 전용 속성

class Config {
  readonly apiUrl: string;

  constructor(apiUrl: string) {
    this.apiUrl = apiUrl;
  }
}

const cfg = new Config('https://example.com');
console.log(cfg.apiUrl); // ✅
cfg.apiUrl = 'https://new.com'; // ❌ Error: Cannot assign

readonly는 **한 번만 초기화할 수 있고, 변경은 불가능**합니다.

💡 주로 **환경 설정 객체**, **불변 리터럴**, **id 값** 등에 사용됩니다.


📐 요약 표

제한자접근 가능 범위상속 클래스클래스 외부
public어디서나 가능
private해당 클래스 내부
protected해당 + 하위 클래스
readonly읽기 전용⭕ (변경 ❌)

🧠 실무 팁

  • private은 외부 접근을 막아 안전한 상태 유지에 사용
  • protected는 확장 가능한 기반 클래스에 활용
  • readonly는 설정, 상수, 식별자(id) 등에 사용
  • public은 명시적 작성 없이 생략 가능 (기본)

📘 다음 글 예고

👉 추상 클래스 vs 인터페이스 – 공통점과 차이점, 언제 어떤 걸 써야 할지 정리합니다.

댓글