TypeScript - Public, Private, Protected(접근제한자)

김서영·2024년 2월 21일
0

Public


어디에서나 접근할 수 있으며 생략 가능한 default 값

class Hello {
  name: string

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

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

const hello = new Hello('seoyeong')
hello.greeting() //'hi seoyeong!'

Private


해당 클래스의 인스턴스에서만 접근 가능

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

const hello = new Hello('seoyeong')
hello.name // Property 'name' is private and only accessible within class 'Hello'.

이렇게 작성하면 에러가 발생한다.
그리고 서브클래스에서 name을 public으로 바꿔주려고 해도 에러 발생!

class Hi extends Hello {
  constructor(public name: string) {
    super(name)
  }
  // Class 'Hi' incorrectly extends base class 'Hello'.
  // Property 'name' is private in type 'Hello' but not in type 'Hi'.ts(2415)
}

Protected


해당 클래스 혹은 서브클래스의 인스턴스에서만 접근 가능

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

  greeting() {
    console.log(`hi ${this.name}!, my name is ${this.myname()}!`)
  }

  protected myname() {
    return 'js'
  }
}

const hello = new Hello('seoyeong')
hello.greeting() // 'hi seoyeong!, my name is js!'

// 2. 서브클래스에서 접근
class Hi extends Hello {}

const hi = new Hi('seoyeong')
hi.greeting() // 'hi seoyeong!, my name is js!'

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

profile
개발과 지식의 성장을 즐기는 개발자

0개의 댓글

관련 채용 정보