c++ 접근 제어자와 거의 동일
다른 점은 멤버 변수 앞에 private나 protected를 각각 붙혀서 사용.
접근 제어자는 생성자 매개변수에 직접 설정 가능하다.
이 경우 필드 선언과 초기화 코드를 생략할 수 있다.
public, private, protected 세 가지가 있음public: 어디서든 접근 가능 (기본값)private: 클래스 내부에서만 접근 가능protected: 클래스 내부 + 파생 클래스에서만 접근 가능타입스크립트에서 제공하는 기능으로,
클래스의 필드나 메서드에 대해 외부에서의 접근 범위를 설정할 수 있다.
사용 가능한 접근 제어자는 다음 세 가지이다:
public: 어디서든 접근 가능 (기본값)private: 클래스 내부에서만 접근 가능protected: 클래스 내부 또는 파생 클래스에서만 접근 가능class Employee {
name: string;
age: number;
position: string;
constructor(name: string, age: number, position: string) {
this.name = name;
this.age = age;
this.position = position;
}
work() {
console.log("일함");
}
}
const employee = new Employee("이정환", 27, "developer");
employee.name = "홍길동"; // ✅ 가능
employee.age = 30; // ✅ 가능
employee.position = "디자이너"; // ✅ 가능
명시적으로 public을 붙여도 결과는 동일하다.
class Employee {
private name: string;
public age: number;
public position: string;
constructor(name: string, age: number, position: string) {
this.name = name;
this.age = age;
this.position = position;
}
work() {
console.log(`${this.name}이 일함`);
}
}
const employee = new Employee("이정환", 27, "developer");
employee.name = "홍길동"; // ❌ 오류: private 접근 불가
employee.age = 30; // ✅
private 필드는 클래스 외부에서 접근이 불가하다.
단, 클래스 내부 메서드에서는 사용 가능하다.
class Employee {
private name: string;
protected age: number;
public position: string;
constructor(name: string, age: number, position: string) {
this.name = name;
this.age = age;
this.position = position;
}
work() {
console.log(`${this.name}이 일함`);
}
}
class ExecutiveOfficer extends Employee {
func() {
this.age; // ✅ protected 접근 가능
this.name; // ❌ private 접근 불가
}
}
const employee = new Employee("이정환", 27, "developer");
employee.age = 30; // ❌ 외부 접근 불가
employee.position = "디자이너"; // ✅
접근 제어자는 생성자 매개변수에 직접 설정 가능하다.
이 경우 필드 선언과 초기화 코드를 생략할 수 있다.
class Employee {
constructor(
private name: string,
protected age: number,
public position: string
) {}
work() {
console.log(`${this.name} 일함`);
}
}
위 코드에서 this.name = name 같은 코드가 없어도
자동으로 필드 선언 + 초기화가 함께 이루어진다.