글 작성자: 망고좋아
반응형

🎯 타입스크립트 Class 접근 제어자

  • 속성 또는 메서드로의 접근을 제한하기 위해 사용한다.
  • TypeScript에는 3종류의 접근 제어자가 존재한다.
  • public > protected > private
  • Java와 다르게 package 개념이 없어 default 접근 제어자는 존재하지 않는다.

 

📝 접근 제어자 - public

class Animal {
    public name: string
    constructor(theName: string) {
        this.name = theName;
    }
}

new Animal("Cat").name;
  • 프로그램 내에서 선언된 멤버들이 자유롭게 접근할 수 있다.
  • TS에서 멤버는 기본적으로 public으로 선언된다.
  • 명시적으로 멤버를 public으로 표시할 수도 있다.

 

📝 접근 제어자 - private

class Animal {
    private name: string
    constructor(theName: string) {
        this.name = theName;
    }
}

new Animal("Cat").name; // error
  • 멤버가 포함된 클래스 외부에서의 접근을 막음
  • private 변수를 외부에서 접근하게 하려면 public 메서드를 제공해야 함 ⇒ Getter, Setter (?)
  • 정보 은닉(Encapsulation) : 캡슐화시키다 ⇒ 같은 클래스끼리만 접근 가능
  • TypeScript는 구조적인 타입 시스템이다. 두 개의 다른 타입을 비교할 때 어디서 왔는지 상관없이 모든 멤버의 타입이 호환된다면, 그 타입들 자체가 호환 가능하다고 말한다.
  • 그러나 privateprotected 멤버가 있는 타입들을 비교할 때는 타입을 다르게 처리한다.
  • 호환된다고 판단되는 두 개의 타입 중 한쪽에서 private 멤버를 가지고 있다면, 다른 한쪽도 무조건 동일한 선언에 private 멤버를 가지고 있어야 한다. 이것은 protected 멤버에도 적용된다.
class Animal {
  private name: string;
  constructor(theName: string) {
    this.name = theName;
  }
}

class Rhino extends Animal {
  constructor() {
    super("Rhino");
  }
}

class Employee {
  private name: string;
  constructor(theName: string) {
    this.name = theName;
  }
}

let animal = new Animal("Goat");
let rhino = new Rhino();
let employee = new Employee("Bob");

animal = rhino;
animal = employee; // 오류: 'Animal'과 'Employee'은 호환될 수 없음.

 

📝 접근 제어자 - protected

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

class Employee extends Person {
  private department: string;

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

  public getElevatorPitch() {
    return `Hello, my name is ${this.name} and I work in ${this.department}.`;
  }
}

let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name); // 오류
  • 멤버가 포함된 클래스와 그 하위 클래스 접근 가능
  • 외부에서의 접근을 막음
  • Person에서 파생된 Employee의 인스턴스 메서드에서는 name을 사용할 수 있다.
  • 즉, protected로 선언된 멤버를 파생된 클래스 내에서 접근할 수 있다는 점만 제외하면 private지정자와 매우 유사하게 동작한다.
  • Person 외부에서 name을 사용할 수 없지만, EmployeePerson에서 파생되었기 때문에 Employee의 인스턴스 메서드 내에서는 여전히 사용할 수 있다.
class Person {
  protected name: string;
  protected constructor(theName: string) {
    this.name = theName;
  }
}

// Employee는 Person을 확장할 수 있습니다.
class Employee extends Person {
  private department: string;

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

  public getElevatorPitch() {
    return `Hello, my name is ${this.name} and I work in ${this.department}.`;
  }
}

let howard = new Employee("Howard", "Sales");
let john = new Person("John"); // 오류: 'Person'의 생성자는 protected 입니다.
  • 생성자 또한 protected로 표시될 수도 있습니다. 이는 클래스를 포함하는 클래스 외부에서 인스턴스화 할 수 없지만 확장할 수 있음을 의미한다.

 

🏷 요약

접근 제어자 같은 클래스 자식 클래스 그 외 영역
public O O O
protected O O X
private O X X

 

📌 참고

 
반응형