Today Sangmin Learned
728x90

배운 것, 공부한 것, 메모할 것

1. TypeScript

  - 클래스 마무리

2. React

  - 테스팅 복습, Redux-thunk 복습

3. 컴활

  - 3과목 풀고, 이기적 필기 빈출인강 2과목 두개듣기

1. TypeScript: 접근 제어자 코드 간소화

class Department {
  public id: string;
  private name: string;

  constructor(id: string, name: string) {
    this.id = id;
    this.name = name;
  }
  // 후략
}

id, name 각각에 대해 외부 접근 여부를 설정하기 위해서는 public, private로 접근 제어자처리를 해줘야 한다. 이렇게 되면 실제 저 값들을 사용하는 constructor 함수의 파라미터로서 들어가는 값들 또한 타이핑이 되어야 한다. 코드의 효율성이 떨어진다.

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

  constructor(private readonly id: string, public name: string) {}

  addEmployee(employees: string) {
    this.id = 'a2'; // error TS2540: Cannot assign to 'id' because it is a read-only property.
    this.employees.push(employee);
  }
}

constructor 함수의 파라미터로서 들어가는 id와 name 각각에 대해 이름 앞에 public 혹은 private를 붙여준다면, 상단의 비효율적인 코드를 작성할 필요도 없으며 함수 내부에서 this.id = id로 지정해 줄 필요도 없어진다.

+) 추가로 readonly를 지정할 수도 있는데, 이 경우 Class 내부 메소드라고 하더라도 readonly 처리를 해 둔 프로퍼티의 값은 절대 바꿀 수 없다.

class Product {
  title: string;
  price: number;
  private isListed: boolean;

  constructor(name: string, pr: number) {
    this.title = name;
    this.price = pr;
    this.isListed = true;
  }
}

위 코드를 간소화하면 아래와 같이 된다. 여기서 따로 처리를 해주지 않은 것들은 전부 public 처리를 하면 된다.

class Product {
  private isListed: boolean;

  constructor(public title: string, public price: number ) {
    this.isListed = true;
  }
}

2. TypeScript: 클래스 상속 및 protected 접근 제어자

한편 private 처리를 하면 상속받은 클래스에서도 접근할 수가 없게 되는데, 클래스 외부에서의 모든 접근을 차단하는 private 대신 상속받은 클래스에 대해서는 접근할 수 있게 하기 위해서는 protected를 사용하면 된다.

class Department {
  protected employees: string[] = [];
  addEmployee(employee: string) {
    this.employees.push(employee)
    // 배열에 추가하는 메소드
  }
    printEmployeeInformation() {
    console.log(this.employees.length);
    console.log(this.employees);
    // 배열의 길이 및 배열 자체를 콘솔에 출력하는 메소드
  }
}

class EngineeringDepartment extends Department {
  constructor(id: string, private reports: string[]) {
    super(id);
    // 다른 클래스를 상속 받는 클래스에 고유 생성자를 추가하려면 super()를 호출해야함.
  }
  addEmployee(name: string) {
    if (name === 'steadily') {
      return;
      // 이름이 steadily면 Employee로서 추가하지 않음
    }
    this.employees.push(name);
  }
}

const engineering = new EngineeringDepartment("2", []);
engineering.addEmployee('steadily'); // not working
engineering.addEmployee('worked');
accounting.printEmployeeInformation(); // ['worked']

2행에서 employees가 private로 설정이 되어있다면

error TS2341: Property 'employees' is private and only accessible within class 'Department'

라는 오류가 뜨게 된다.여기서 protected로 바꿔줌으로써 상속받은 클래스에서 또한 사용할 수 있게 된다. 그 외에 기본적으로 부모 클래스의 메소드들은 상속받은 자식 클래스에서도 모두 사용할 수 있기 때문에 engineering.addEmployee 가 잘 실행된 것이며, name이 steadily일 때는 return문을 통해 걸러냈으므로 engineering.printEmployeeInformation() 으로 확인을 해보면 steadily는 들어가있지 않고 worked만 들어가 있게 된다.

profile

Today Sangmin Learned

@steadily-worked

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!