TypeScript - 접근제한자 (public, protected, private)

김승ㅈIT·2023년 4월 26일

TypeScript

목록 보기
2/2
post-thumbnail

TypeScript에서는 접근 제한자(Access modifier)인 public, protected, private를 지원하며, 이를 통해 외부에서 특정 메서드나 프로퍼티에 접근 범위를 지정할 수 있다.

🔥public

[TypeScript Handbook]

public은 어디에서나 접근할 수 있으며 생략 가능한 default 값이다.

class Greeter {
  public greet() {
    console.log("hi!");
  }
}
const g = new Greeter();
g.greet();


🔥protected

[TypeScript Handbook]
protected는 자신이 선언된 클래스의 하위 클래스에서만 볼 수 있습니다.

class Greeter {
  public greet() {
    console.log("Hello, " + this.getName());
  }
  protected getName() {
    return "hi";
  }
}
 
class SpecialGreeter extends Greeter {
  public howdy() {
    // OK to access protected member here
    console.log("Howdy, " + this.getName());
  }
}
const g = new SpecialGreeter();
g.greet(); // OK
g.getName();

getName()Greeter내부에서와 자식클래스 내부에서만 접근이 가능하다. 그렇기 때문에 자식인 SpecialGreeter()의 메소드 인 howdy 안에서 getName()을 사용할 수 있다. 하지만 외부인 인스턴스에서는 사용할 수 없다. 그렇기 때문에 g.getName() 즉, new SpecialGreeter().getName()은 컴파일 오류가 생긴다.



🔥private

[TypeScript Handbook]

privateprotected는 비슷하지만 private는 하위 클래스 즉, 자식 클래스와 서브 클래스에서도 액세스를 허용하지 않습니다.

class Base {
  private x = 0;
}
const b = new Base();
// Can't access from outside the class
console.log(b.x);

class Base {
  private x = 0;
}

class Derived extends Base {
  showX() {
    // Can't access in subclasses
    console.log(this.x);
  }
}

🔥public, protected, private 테이블 비교

접근가능성publicprotectedprivate
클래스 내부
자식 클래스 내부
클래스 인스턴스

참고자료
https://www.howdy-mj.me/typescript/access-modifiers

0개의 댓글