TypeScript-섹션6. 클래스-접근 제어자(3)

손주완·2025년 7월 13일

Typescript Section6

목록 보기
3/4

✅선요약

c++ 접근 제어자와 거의 동일
다른 점은 멤버 변수 앞에 private나 protected를 각각 붙혀서 사용.
접근 제어자는 생성자 매개변수에 직접 설정 가능하다.
이 경우 필드 선언과 초기화 코드를 생략할 수 있다.

  • 접근 제어자는 public, private, protected 세 가지가 있음
  • public: 어디서든 접근 가능 (기본값)
  • private: 클래스 내부에서만 접근 가능
  • protected: 클래스 내부 + 파생 클래스에서만 접근 가능
  • 생성자 매개변수에 접근 제어자를 붙이면 필드 선언 및 초기화가 자동으로 이루어짐
  • 접근 제어자 사용 시 코드 간결성과 정보 은닉성이 향상됨

타입스크립트 접근 제어자

✅ 접근 제어자란?

타입스크립트에서 제공하는 기능으로,
클래스의 필드나 메서드에 대해 외부에서의 접근 범위를 설정할 수 있다.

사용 가능한 접근 제어자는 다음 세 가지이다:

  • public: 어디서든 접근 가능 (기본값)
  • private: 클래스 내부에서만 접근 가능
  • protected: 클래스 내부 또는 파생 클래스에서만 접근 가능

📌 public (기본 접근 제어자)

class Employee {
  name: string;
  age: number;
  position: string;

  constructor(name: string, age: number, position: string) {
    this.name = name;
    this.age = age;
    this.position = position;
  }

  work() {
    console.log("일함");
  }
}

const employee = new Employee("이정환", 27, "developer");

employee.name = "홍길동";      // ✅ 가능
employee.age = 30;            // ✅ 가능
employee.position = "디자이너"; // ✅ 가능

명시적으로 public을 붙여도 결과는 동일하다.


🔐 private

class Employee {
  private name: string;
  public age: number;
  public position: string;

  constructor(name: string, age: number, position: string) {
    this.name = name;
    this.age = age;
    this.position = position;
  }

  work() {
    console.log(`${this.name}이 일함`);
  }
}

const employee = new Employee("이정환", 27, "developer");

employee.name = "홍길동"; // ❌ 오류: private 접근 불가
employee.age = 30;        // ✅

private 필드는 클래스 외부에서 접근이 불가하다.
단, 클래스 내부 메서드에서는 사용 가능하다.


🛡 protected

class Employee {
  private name: string;
  protected age: number;
  public position: string;

  constructor(name: string, age: number, position: string) {
    this.name = name;
    this.age = age;
    this.position = position;
  }

  work() {
    console.log(`${this.name}이 일함`);
  }
}

class ExecutiveOfficer extends Employee {
  func() {
    this.age;  // ✅ protected 접근 가능
    this.name; // ❌ private 접근 불가
  }
}

const employee = new Employee("이정환", 27, "developer");

employee.age = 30;   // ❌ 외부 접근 불가
employee.position = "디자이너"; // ✅

✍ 생성자에서 필드 생략하기

접근 제어자는 생성자 매개변수에 직접 설정 가능하다.
이 경우 필드 선언과 초기화 코드를 생략할 수 있다.

class Employee {
  constructor(
    private name: string,
    protected age: number,
    public position: string
  ) {}

  work() {
    console.log(`${this.name} 일함`);
  }
}

위 코드에서 this.name = name 같은 코드가 없어도
자동으로 필드 선언 + 초기화가 함께 이루어진다.


0개의 댓글