티스토리 뷰

자바스크립트에서는 class 사용시 마땅히 내부의 값을 은닉화 할 수 있는 방법이 없었으나

타입스크립트에서는 접근제한자인 public, protected, private를 지원한다.

이를 통해, 외부에서 특정 메소드나 프로퍼티에 접근범위를 지정 할 수 있다.

 

public은 어디에서나 접근 가능하며 생략가능한 default값.


public


class Aboutme {
  name: string

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

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

const me = new Aboutme('sophie')
me.greet() // output: 'hi! sophie'

 

name을 선언하기위해서는 꽤나 양이 많았으나. public을 사용하면 코드양을 확 줄일 수 있다.

 

class Aboutme {
  constructor(public name: string) {}
  // 생략
}

protected


protected는 해당 클래스 혹은 서브클래스의 인스턴스에서만 접근이 가능하다.

// 1. 해당 클래스에서 접근
class Aboutme {
  constructor(public name: string) {}

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

  protected test() {
    return 'test'
  }
}

const me = new Aboutme('sophie')
me.greet() // output: 'hi! sophie, log: test'

// 2. 서브클래스에서 접근
class Aboutme2 extends Aboutme {}

const a2 = new Aboutme2('bomba')
a2.greet() // output: 'hi bomba, log: test'

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

 

class Aboutme2 extends Aboutme {
  test() {
    return 'override'
  }
}

const me = new Aboutme2('bomba')
me.greet() // output: 'hi bomba, log: override'

const test = me.test()
console.log(test) // output: 'override'

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

 


private


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

 

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

const me = new Aboutme('sophie')
me.name // Property 'name' is private and only accessible within class 'Aboutme'.

위의 예시에서 name을 가져오려하려면, 위와 같은 에러가 뜬다.

그리고 서브클래스에서 name을 public으로 바꾸어주려고 해도 에러가 뜬다.

 

class Aboutme2 extends Aboutme {
  constructor(public name: string) {
    super(name)
  }
  // Class 'Aboutme2' incorrectly extends base class 'Aboutme'.
  // Property 'name' is private in type 'Aboutme' but not in type 'Aboutme2'.ts(2415)
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함