접근 제어자
접근 제어자는 타입스크립트에서만 제공되는 기능으로, 클래스의 특정 필드나 메서드를 접근할 수 있는 범위를 설정하는 기능이다.
public
public으로 설정된 필드는 클래스 외부에서 자유롭게 접근하고 수정할 수 있다.
class Employee {
name: string;
hp: number;
position: string;
constructor(name: string, hp: number, position: string) {
this.name = name;
this.hp = hp;
this.position = position;
}
work() {
console.log("일함");
}
}
const employee = new Employee("고견", 90, "developer");
employee.name = "devmark";
employee.hp = 79;
위 코드에서 name, hp, position은 기본적으로 public이기 때문에 인스턴스를 통해 자유롭게 값을 읽고 수정할 수 있다.
private
private로 설정된 필드는 클래스 내부에서만 접근할 수 있으며, 외부에서는 접근할 수 없다.
class Employee {
private name: string;
public hp: number;
public position: string;
// ...
}
}

name 필드를 private으로 설정했기 때문에 클래스 외부에서 접근하려고 하면 오류가 발생한다.
private 필드는 상속받은 자식 클래스에서도 접근할 수 없다.

부모 클래스의 private인 name을 자식 클래스에서도 접근할 수 없기 때문에 이렇게 에러가 발생한다.
protected
protected로 설정된 필드는 클래스 외부에서는 접근할 수 없지만, 상속받은 자식 클래스에서는 접근할 수 있다.
class Employee {
private name: string;
protected hp: number;
public position: string;
// ...
}
이제 hp필드는 protected로 설정되어 자식 클래스에서 접근할 수 있다.
class ExcutiveOfficer extends Employee {
officeNumber: number;
constructor(
name: string,
hp: number,
position: string,
officeNumber: number
) {
super(name, hp, position);
this.officeNumber = officeNumber;
}
func() {
this.hp; // ✅
}
}
이렇게 자식 클래스인 ExcutiveOfficer에서는 hp에 접근할 수 있지만,
다음과 같이 클래스 외부에서는 접근할 수 없다.
const employee2 = new Employee("고견", 90, "developer");
employee2.hp = 79; // ❌
필드 생략하기
접근 제어자는 생성자의 매개변수에도 설정할 수 있다.
class Employee {
constructor(
private name: string,
protected hp: number,
public position: string
) {
this.name = name;
this.hp = hp;
this.position = position;
}
// ...
}
그러나 생성자에 접근 제어자를 설정하면 동일한 이름의 필드를 선언하지 못하게 된다.
class Employee {
private name: string; // ❌
protected age: number; // ❌
public position: string; // ❌
constructor(
private name: string, // ❌
protected hp: number, // ❌
public position: string // ❌
) {
this.name = name;
this.hp = hp;
this.position = position;
}
// ...
}
그 이유는 생성자 매개변수에 name, hp, position처럼 접근 제어자가 설정되면 자동으로 필드도 함께 선언되기 때문이다. 즉, 동일한 이름으로 필드를 중복 선언할 수 없게 된다.
따라서, 다음과 같이 중복된 필드 선언을 모두 제거해 주어야 한다.
class Employee {
constructor(
private name: string,
protected hp: number,
public position: string
) {
this.name = name;
this.hp = hp;
this.position = position;
}
// ...
}
또한, 접근 제어자가 설정된 매개변수들은 this.필드 = 매개변수 할당이 자동으로 수행된다.
따라서 위 코드의 name, hp, position은 모두 this 객체의 프로퍼티 값으로 자동 설정되기 때문에 다음과 같이 생성자 내부의 코드를 제거해도 된다.
class Employee {
constructor(
private name: string,
protected hp: number,
public position: string
) {}
// ...
}
그러므로 타입스크립트에서 클래스를 사용할 때에는 보통 생성자 매개변수에 접근 제어자를 설정하여 필드 선언과 생성자 내부 코드를 생략하는 것이 훨씬 간결하고 빠르게 코드를 작성할 수 있어 좋다.
'TIL' 카테고리의 다른 글
| [TS] 클래스와 접근제어자 사용 연습 (0) | 2025.11.03 |
|---|---|
| [TS] 인터페이스로 구현하는 클래스 (implements) (0) | 2025.11.03 |
| [TS] 클래스 (0) | 2025.11.01 |
| [TS] 인터페이스 선언 합침 (0) | 2025.11.01 |
| [TS] 인터페이스 확장 (0) | 2025.11.01 |
