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)
'타입스크립트( TypeScript)' 카테고리의 다른 글
[타입스크립트] tsconfig.json "lib" 속성 (0) | 2022.12.04 |
---|---|
[타입스크립트] 타입스크립트 --watch 속성 과 exclude, include 속성 (1) | 2022.11.30 |
[타입스크립트] 함수 Function 타입 (0) | 2022.11.16 |
타입스크립트 리터럴 타입(Literal Type) (0) | 2022.11.12 |
타입스크립트 유니온(Union) (0) | 2022.11.12 |