본문 바로가기
타입스크립트( TypeScript)

[타입스크립트] class 접근 제어자 private, public

by BillyCho 2022. 12. 4.

class의 접근 제어자 private, public을 다루어보자

class Department {
   name: string;
   private employees: string[] = [];

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

  describe(this: Department) {
    console.log('Department: ' + this.name);
  }

  addEmployee(employee: string) {
    this.employees.push(employee);
  }
}

Department라는 class가 존재한다

addEmployee 함수를 이용해보자

 

const accounting = new Department('Accounting');
accounting.addEmployee('Thomas');
accounting.addEmployee('Grace');
// result -> ['Thomas', 'Grace']

 

위의 코드를 실행하면 정상적으로 작동한다

 

 

다음 임의로 1번쨰 인덱스 값을 바꾸면 어떻게 될까 ?

accounting.employees[1] = 'Changed User'

 

예상대로 값이 바뀌게 된다

 

이처럼 class를 구성하면서 데이터의 특성에 나눠서 접근 권한을 다르게 설정하고 싶을 떄 private, public 접근 제어자를 사용할 수 있다

 

class Department {
   name: string;
   private employees: string[] = [];

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

  describe(this: Department) {
    console.log('Department: ' + this.name);
  }

  addEmployee(employee: string) {
    this.employees.push(employee);
  }
}

바로 위처럼 employees 앞에 private 만 작성해주면 된다

 

그러면 인덱스를 통해 변경하려된 코드는 아래의 에러가 발생한다

 

Property 'employees' is private and only accessible within class 'Department'.ts(2341)