Eun_Frontend
  • [TypeScript] TypeScript 접근제한자(public, protected, private, readonly) [5/26 study]
    2024년 05월 25일 15시 23분 46초에 업로드 된 글입니다.
    작성자: 동혁이

     

     

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

     

     

     

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

     

    ❗️public

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

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

     

    ❗️protected

    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();
    Property 'getName' is protected and only accessible within class 'Greeter' and its subclasses.

    단, 서브클래스에서 protected로 된 값을 public으로 오버라이딩한다면 해당 값은 public으로 취급된다.

    오버라이딩할 경우, 상위클래스의 return 타입과 같아야 한다 그렇지 않으면 에러를 반환한다.

     

    ❗️private

    private는 해당 클래스의 인스턴스에서만 접근 가능하다.

    class Base {
      private x = 0;
    }
    const b = new Base();
    // Can't access from outside the class
    console.log(b.x);
    Property 'x' is private and only accessible within class 'Base'.
    class Derived extends Base {
      showX() {
        // Can't access in subclasses
        console.log(this.x);
    Property 'x' is private and only accessible within class 'Base'.
      }
    }

    비공개 멤버는 파생 클래스에 표시되지 않으므로 파생 클래스에서 해당 멤버의 공개 범위를 늘릴 수 없습니다.

    class Base {
      private x = 0;
    }
    class Derived extends Base {
    Class 'Derived' incorrectly extends base class 'Base'.
      Property 'x' is private in type 'Base' but not in type 'Derived'.
      x = 1;
    }

    서브클래스를 public으로 바꾸어주려고 하면 에러가 뜬다.

     

    ❗️readonly

    필드 앞에 읽기 전용 수정자를 붙일 수 있습니다. 이렇게 하면 생성자 외부에서 필드에 할당할 수 없습니다.

    class Greeter {
      readonly name: string = "world";
     
      constructor(otherName?: string) {
        if (otherName !== undefined) {
          this.name = otherName;
        }
      }
     
      err() {
        this.name = "not ok";
    Cannot assign to 'name' because it is a read-only property.
      }
    }
    const g = new Greeter();
    g.name = "also not ok";
    Cannot assign to 'name' because it is a read-only property.

     

    ❗️참고

    https://www.typescriptlang.org/docs/handbook/2/classes.html#readonly

     

    Documentation - Classes

    How classes work in TypeScript

    www.typescriptlang.org

     

    ❗️마무리

    class문법을 이제 막 배우고 있는데 접근 제한자 부분이 이해가 되면서 안되는 느낌이라서 찾아보고 포스팅 해보았다 도움이 되었으면 좋겠다 오늘도 화이팅🔥

    댓글