JavaScript에서는 클래스 내부의 메서드나 프로퍼티를 은닉화할 수 있는 방법이 없었다.

하지만 TypeScript에서는 public, private, protected 접근 제한자를 제공하기 때문에 메서드나 프토퍼티의 접근 범위를 지정할 수 있다.

public

public은 어디에서나 접근 가능하며 기본적으로 모든 메서드와 프로퍼티는 public이다.

class Hello {
  name: string

  constructor(name: string) {
    this.name = name
  }

// public 생략 가능public greet() {
    console.log(`hi! ${this.name}`)
  }
}

const hello = new Hello('wow')
hello.greet()// hi! wow

protected

protected는 해당 클래스 혹은 서브 클래스에서만 접근할 수 있다.

class Hello {
  constructor(public name: string) {}

  greet() {
    console.log(`hi! ${this.name}, log: ${this.test()}`)
  }

  protected test() {
    return 'test'
  }
}

const hello = new Hello('kmj')
hello.greet()// hi! kmj, log: testclass Hi extends Hello {}

const hi = new Hi('howdy')
hi.greet()// hi howdy, log: test

서브 클래스에서 public으로 오버라이딩하면 public으로 변한다.

class Hi extends Hello {
  override test() {
    return 'override'
  }
}

const hi = new Hi('howdy')
hi.greet()// hi howdy, log: overrideconst test = hi.test()
console.log(test)// override

private

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

class Hello {
  constructor(private name: string) {}
}

const hello = new Hello('kmj')
hello.name// Error

주의할 점

private, protected로 지정한 메서드나 프로퍼티는 key값으로 접근이 가능하다.

const hello = new Hello('kmj')
console.log(hello['name'])// kmj