• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    해결됨

interface를 사용할 때 private 사용방법은?

23.07.20 16:50 작성 조회수 304

0

impolements러 interface를 받아 class를 만들때 private이 안되는 오류를 보여주셨는데요

interface를 사용하지 않고 그냥 class안에서 type을 지정하는 방법, abstract class를 이용하는 방법 모두 이해됬습니다.

하지만 interface를 사용하면 private, protected 사용이 불가한 것인지 잘 모르겠어서 질문을 올립니다.

 

 

구글링해본결과

class내에 속성으로 만들고 getter, setter를 이용하는 것으로 우회하는 방법을 사용하더라구요.

(https://stackoverflow.com/questions/37791947/how-to-define-a-private-property-when-implementing-an-interface-in-typescript)

 

이렇게 했을 때 private의 기능인 class 밖에서는 호출 할 수 없다고 위반되는 결과가 나옵니다.

 

어떤식으로 해결 해야 할까요?

interface Interface {
  readonly a: string;
  b: number;
}

class TSClass implements Interface {
  private readonly _a: string = "init";
  get a() {
    return this._a;
  }

  protected _b: number = 1;
  get b() {
    return this._b;
  }
  set b(v: number) {
    this._b = v;
  }

  c: string = "기본값이 public";

  method() {
    console.log(this._a);
    console.log(this._b);
    console.log(this.c);
  }
}

class inheritClass extends TSClass {
  method() {
    console.log(this._a); // error
    console.log(this.a); // 가능..
    console.log(this._b);
    console.log(this.b);
    console.log(this.c);
  }
}

new inheritClass()._a; // error
new inheritClass().a; // 가능...
new inheritClass()._b; // error
new inheritClass().b; // 가능..
new inheritClass().c;

 

답변 1

답변을 작성해보세요.

1

인터페이스는 원래 그 특성 자체가 public입니다. private인 것은 인터페이스로 만들 필요도 이유도 없습니다.