본문 바로가기
typescript

접근 제한자

by momomoo 2024. 7. 1.

private 키워드는 TypeScript에서 접근 제한자(Access Modifier) 중 하나로, 클래스의 속성이나 메서드가 클래스 외부에서 접근할 수 없도록 제한합니다. private로 선언된 속성이나 메서드는 해당 클래스 내부에서만 접근할 수 있으며, 클래스의 인스턴스나 하위 클래스에서는 접근할 수 없습니다.

 

접근 제한자의 종류

 

TypeScript에는 세 가지 주요 접근 제한자가 있습니다:

 

1. public: 기본 접근 제한자로, 어디서나 접근할 수 있습니다.

public 접근 제한자는 클래스의 속성이나 메서드가 어디서나 접근 가능함을 의미합니다. 이는 TypeScript에서 기본 접근 제한자입니다. 명시적으로 지정하지 않으면 기본적으로 public으로 간주됩니다.

 

class Person {
  public name: string;
  public age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  public greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

const person = new Person("Alice", 30);
console.log(person.name); // "Alice"
console.log(person.age);  // 30
person.greet();           // "Hello, my name is Alice and I am 30 years old."

 

 

2. private: 클래스 내부에서만 접근할 수 있습니다.

private 접근 제한자는 클래스의 속성이나 메서드가 클래스 외부에서 접근할 수 없음을 의미합니다. private으로 선언된 멤버는 해당 클래스 내부에서만 접근할 수 있습니다.

 

class Person {
  private name: string;
  private age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  public getDetails() {
    return `Name: ${this.name}, Age: ${this.age}`;
  }
}

const person = new Person("Bob", 25);
console.log(person.getDetails()); // "Name: Bob, Age: 25"

// 아래 코드는 오류를 발생시킵니다.
console.log(person.name); // 오류: 'name' 속성은 private이므로 클래스 'Person' 외부에서 접근할 수 없습니다.
console.log(person.age);  // 오류: 'age' 속성은 private이므로 클래스 'Person' 외부에서 접근할 수 없습니다.

 

 

3. protected: 클래스 내부와 하위 클래스에서만 접근할 수 있습니다.

protected 접근 제한자는 클래스의 속성이나 메서드가 해당 클래스와 하위 클래스에서만 접근할 수 있음을 의미합니다. protected로 선언된 멤버는 클래스 외부에서는 접근할 수 없습니다.

 

class Person {
  protected name: string;
  protected age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

class Employee extends Person {
  private employeeId: number;

  constructor(name: string, age: number, employeeId: number) {
    super(name, age);
    this.employeeId = employeeId;
  }

  public getEmployeeDetails() {
    return `Name: ${this.name}, Age: ${this.age}, Employee ID: ${this.employeeId}`;
  }
}

const employee = new Employee("Charlie", 40, 12345);
console.log(employee.getEmployeeDetails()); // "Name: Charlie, Age: 40, Employee ID: 12345"

// 아래 코드는 오류를 발생시킵니다.
console.log(employee.name); // 오류: 'name' 속성은 protected이므로 클래스 'Employee' 외부에서 접근할 수 없습니다.
console.log(employee.age);  // 오류: 'age' 속성은 protected이므로 클래스 'Employee' 외부에서 접근할 수 없습니다.